思路如下:
- 首先 遍历链表,得到结点个数count,不包括哨兵结点
- for大循环,while小循环。其中for循环的i是为了限制while循环的每一趟的循环次数num,考虑对数组进行的冒泡排序,n个元素进行排序,第一趟n-1次比较,第二趟n-2次,。。最后之比较一次。
- 代码如下
#include <stdio.h> #include<stdlib.h> typedef struct LinkNode { int data; struct LinkNode*next; }node; node* create();//创建带哨兵结点的链表 node* bubble(node*head);//对链表进行冒泡排序 void printfList(node*head);//输出链表 int main() { node*head=create(); bubble(head); printfList(head); } node* create() { node*head=(node*)malloc(sizeof(node)); head->next=NULL; node*tail=head; int x; scanf("%d",&x); while(x!=-1) { node*p=(node*)malloc(sizeof(node)); p->data=x; p->next=tail->next; tail->next=p; tail=tail->next; scanf("%d",&x); } return head; } node* bubble(node*head) { node*p=head->next; int count=0;//统计节点个数 while(p!=NULL) { count++; p=p->next; } for(int i=0;i<count-1;i++) { int num=count-1-i;//限制while循环次数 node*front=head; node*p=head->next; node*q=p->next; while(num!=0) { if(p->data>q->data) { p->next=q->next; front->next=q; q->next=p; front=front->next; q=p->next; } else{ front=front->next; p=p->next; q=q->next; } num--; } } return head; } void printfList(node*head) { node*p=head->next; while(p!=NULL) { printf("%d ",p->data); p=p->next; } }