1、单链表冒泡排序(从小到大)
2007年考到,前几年也考到过
仅交换数值。这里的一个出彩点就是关于指针t的,在这之前我也实现过,但是当时没想到用指针t就解决了
1 #include <stdio.h> 2 #include <stdlib.h> 3 #define LEN sizeof(struct node) 4 5 struct node{ 6 int a; 7 struct node *link; 8 }; 9 10 struct node *create(){ 11 struct node *head,*p,*q; 12 head=p=q=(struct node *)malloc(LEN); 13 scanf("%d",&p->a); 14 while(q->a){ 15 p->link=q; 16 p=q; 17 q=(struct node *)malloc(LEN); 18 scanf("%d",&q->a); 19 } 20 p->link=NULL; 21 return head; 22 } 23 24 void sort(struct node *head){ 25 struct node *p,*q,*t; 26 int m,tag; 27 t=NULL; 28 while(head->link!=t){ 29 p=head; 30 q=p->link; 31 tag=0; 32 while(q!=t){//红色部分的处理是我上次写单链表的冒泡排序纠结的点,没有想到的地方 33 if(p->a>q->a){ 34 m=p->a; 35 p->a=q->a; 36 q->a=m; 37 tag=1; 38 } 39 p=q; 40 q=q->link; 41 } 42 t=p; 43 if(tag==0) 44 break; 45 } 46 } 47 int main() 48 { 49 struct node *head,*s; 50 head=create(); 51 sort(head); 52 for(s=head;s;s=s->link) 53 printf("%d ",s->a); 54 return 0; 55 }
运行结果: