1 #include <stdio.h> 2 #include <stdlib.h> 3 /* 4 链表指针交换实现冒泡排序:核心思想:1.每次都从头开始比较 5 2.sh,p,q整体往前走一步(交不交换都要往前走) 6 3.交换完之后p变成q,q变成p,整体往前走,下次交换就会出现混乱,所以p,q还要指向原来的位置才能整体往前走 7 */ 8 typedef struct node 9 { 10 int data; 11 struct node * next; 12 }NODE; 13 NODE * createList() 14 { 15 NODE * head = (NODE *)malloc(sizeof(NODE)); 16 head->next = NULL; 17 18 return head; 19 } 20 void insertNode(NODE * head,int insertData) 21 { 22 NODE * sur = (NODE *)malloc(sizeof(NODE)); 23 sur->data = insertData; 24 25 sur->next = head->next; 26 head->next = sur; 27 } 28 void traverList(NODE * head) 29 { 30 head = head->next; 31 while(head) 32 { 33 printf("%d\n",head->data); 34 head = head->next; 35 } 36 } 37 int lenList(NODE *head) 38 { 39 int len = 0; 40 head = head->next; 41 while(head) 42 { 43 len++; 44 head = head->next; 45 } 46 47 return len; 48 } 49 void pointerPopsort(NODE *head,int len) 50 { 51 NODE * sh,*p,*q,*temp; 52 sh = p = q = NULL; 53 for(int i = 0;i<len-1;i++) 54 { 55 //每次都从头开始比较 56 sh = head; 57 p = sh->next; 58 q = p->next; 59 for(int j = 0;j<len-1-i;j++) 60 { 61 if(p->data > q->data) 62 { 63 //交换指针 64 sh->next = q; 65 p->next = q->next; 66 q->next = p; 67 68 //交换完之后p变成q,q变成p,整体往前走,下次交换就会出现混乱,所以p,q还要指向原来的位置才能整体往前走 69 temp = p; 70 p = q; 71 q = temp; 72 } 73 //sh,p,q整体往前走一步(交不交换都要往前走)、 74 sh = sh->next; 75 p = p->next; 76 q = q->next; 77 78 } 79 } 80 } 81 int main(void) 82 { 83 NODE * head = createList(); 84 for(int i = 0;i<50;i++) 85 insertNode(head,rand()%100); 86 traverList(head); 87 int len = lenList(head); 88 printf("排序后\n"); 89 pointerPopsort(head,len); 90 traverList(head); 91 92 return 0; 93 }
链表指针交换实现冒泡排序
猜你喜欢
转载自www.cnblogs.com/wangchaomahan/p/9715938.html
今日推荐
周排行