冒泡排序(链表实现)
暑假里看到大神的一篇文章,在一个大公司里面试,面试冒泡排序链表版,当时想了写一下,不知该如何写起,就放下了,最近数据结构又重新学习链表,试着写了下,对链表的操作熟练运用吧。调的我很纠结啊。。。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 using namespace std; 6 struct node 7 { 8 int data; 9 struct node *next; 10 }List; 11 struct node *create(int n)//建立顺序链表 12 { 13 int i; 14 struct node *head,*tail,*p; 15 head = new node; 16 head ->next = NULL; 17 tail = head; 18 for(i = 1;i <= n;i ++) 19 { 20 p = new node; 21 p -> next = NULL; 22 scanf("%d",&p->data); 23 tail -> next = p; 24 tail = tail -> next; 25 } 26 return head; 27 } 28 void show(struct node *head)//输出函数 29 { 30 struct node *k; 31 k = head -> next; 32 while(k) 33 { 34 if(k == head->next) 35 printf("%d",k->data); 36 else 37 printf(" %d",k->data); 38 k = k -> next; 39 } 40 printf("\n"); 41 } 42 void Bubblesort(struct node *head,int n)//冒泡排序 43 { 44 int i; 45 struct node *str,*end,*p,*pos,*t; 46 str = head -> next; 47 while(str -> next)//找到链表的末尾 48 { 49 str = str ->next; 50 } 51 end = str -> next;//把末尾给存起来 52 for(i = 1;i <= n-1;i ++) 53 { 54 str = head -> next; 55 pos = head;//存前驱节点 56 while(str -> next != end) 57 { 58 p = str -> next; 59 if(str->data > p->data)//指针交换 60 { 61 t = p -> next; 62 pos -> next = p; 63 p -> next = str; 64 str -> next = t; 65 str = p; 66 } 67 str = str -> next; 68 pos = pos -> next; 69 } 70 end = str; 71 } 72 } 73 int main() 74 { 75 int n; 76 struct node *head; 77 printf("请输入元素个数:\n"); 78 scanf("%d",&n); 79 printf("请输入元素:\n"); 80 head = create(n); 81 Bubblesort(head,n); 82 printf("排序后的序列为:\n"); 83 show(head); 84 return 0; 85 }