链表值排序之冒泡
Posted wangchaomahan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了链表值排序之冒泡相关的知识,希望对你有一定的参考价值。
1 #include <stdio.h> 2 #include <stdlib.h> 3 /* 4 链表值排序之冒泡:核心思想:1.每次都从头开始比较 5 2.推动链表往下走的不在是下标 6 */ 7 typedef struct node 8 { 9 int data; 10 struct node * next; 11 }NODE; 12 NODE * createList() 13 { 14 NODE *head = (NODE *)malloc(sizeof(NODE)); 15 head->next = NULL; 16 17 return head; 18 } 19 void insertNode(NODE *head,int insertData) 20 { 21 NODE * sur = (NODE *)malloc(sizeof(NODE)); 22 sur->data = insertData; 23 24 sur->next = head->next; 25 head->next = sur; 26 return ; 27 } 28 void traverNode(NODE * head) 29 { 30 head = head->next; 31 while(head) 32 { 33 printf("%d ",head->data); 34 head = head->next; 35 } 36 return ; 37 } 38 int lenList(NODE *head) 39 { 40 int len = 0; 41 head = head->next; 42 while(head) 43 { 44 len++; 45 head = head->next; 46 } 47 48 return len; 49 } 50 void sortNode(NODE *head) 51 { 52 int len = lenList(head); 53 NODE * sur = NULL; 54 int temp; 55 for(int i = 0;i<len-1;i++) 56 { 57 sur = head->next; 58 for(int j = 0;j<len-1-i;j++) 59 { 60 if(sur->data > sur->next->data) 61 { 62 temp = sur->data; 63 sur->data = sur->next->data; 64 sur->next->data = temp; 65 } 66 sur = sur->next;//推动链表向前走 67 } 68 } 69 return ; 70 } 71 int main(void) 72 { 73 NODE * head = createList(); 74 for(int i = 0;i<30;i++) 75 { 76 insertNode(head,rand()%100); 77 } 78 printf("排序前 "); 79 traverNode(head); 80 printf("排序后 "); 81 sortNode(head); 82 traverNode(head); 83 84 return 0; 85 }
以上是关于链表值排序之冒泡的主要内容,如果未能解决你的问题,请参考以下文章