|

楼主 |
发表于 2022-5-11 17:11:56
|
显示全部楼层
成功了,成功了,谢谢,那个交换指针的方案,我还是不要研究了(估计我研究不了)
- #include <stdio.h>
- #include <malloc.h>
- #include <time.h>
- #include <stdlib.h>
- struct Node
- {
- int data;
- struct Node *next;
- };
- //带头节点的 头插法
- struct Node * init_link(struct Node * s)
- {
- srand((int)time(NULL));
- struct Node * head=s;
- for(int x=10;x<20;x++)
- {
- struct Node * node1=NULL;
- node1=(struct Node*)malloc(sizeof(struct Node));
- node1->data=rand()%10000;
- node1->next=head;
- head=node1;
- }
- return head;
- }
- int main()
- {
- struct Node * head;
- head=(struct Node*)malloc(sizeof(struct Node));
- head->data=0;
- head->next=NULL;
- head=init_link(head);
- //输出原始链表
- struct Node *pmove=head;
- while (pmove)
- {
- if(pmove->next==NULL) break;
- printf("%4d ",pmove->data);
- pmove=pmove->next;
- }
- printf("\n");
- //准备排序
- struct Node *end=NULL,*q,*p;
- for (p=head; p->next; p=p->next)
- {
- for (q=head;q->next!=end;q=q->next)
- {
- if (q->data>q->next->data)
- {
- int t=q->data;
- q->data=q->next->data;
- q->next->data=t;
- }
- }
- end=q;
- }
- //输出排序后链表
- pmove=head->next;
- while (pmove)
- {
- printf("%4d ",pmove->data);
- pmove=pmove->next;
- }
- return 0;
- }
- /*
- 样例输出:
- PS D:\001> ./w4
- 8227 9821 3215 548 4427 2807 119 6152 7995 7628
- 119 548 2807 3215 4427 6152 7628 7995 8227 9821
- */
复制代码 |
|