1 #include <stdio.h> 2 #define NEWNODE (Node *)malloc(sizeof(Node)) 3 4 typedef struct mynode{ 5 int num; 6 struct mynode *next; 7 }Node; 8 9 Node* creat(){ 10 Node *head=NULL,*p,*q; 11 //head:表頭,q:表尾 12 q=p=NEWNODE; 13 scanf("%d",&p->num); 14 p->next=NULL; 15 while(p->num>0){ 16 if(head==NULL){ 17 head=q=p; 18 }else{ 19 q->next=p; 20 q=p; 21 } 22 p=NEWNODE; 23 scanf("%d",&p->num); 24 p->next=NULL; 25 } 26 return head; 27 } 28 29 void print(Node *head){ 30 Node *p; 31 p=head; 32 while(p) 33 { 34 printf("%d ",p->num); 35 p=p->next; 36 } 37 printf("\n"); 38 } 39 40 int len(Node *head){ 41 int k=0; 42 Node *p; 43 p=head; 44 while(p) 45 { 46 k++; 47 p=p->next; 48 } 49 return k; 50 } 51 52 //選擇排序-交換結點 53 Node *select_sort(Node *head){ 54 Node *begin=NULL,*end=NULL; //有序鏈表的首尾結點指針 55 Node *p; 56 Node *min,*premin; //最小結點及其前一個結點 57 if(!head)return NULL; 58 while(head){ 59 //循環找出無序鏈表中的最小結點min及其前一個結點premin 60 p=head; 61 min=p; 62 while(p->next){ 63 if(min->num>p->next->num){ 64 premin=p; 65 min=p->next; 66 } 67 p=p->next; 68 } 69 //1. 將min接入有序鏈表 70 //如果有序鏈表為NULL 71 if(begin==NULL){ 72 begin=end=min; 73 }else{ 74 end->next=min; 75 end=min; 76 } 77 //2. 在無序鏈表中刪除結點min 78 if(min==head){ 79 head=min->next; 80 }else{ 81 premin->next=min->next; 82 } 83 } 84 end->next=NULL; 85 return begin; 86 } 87 88 //冒泡排序-交換值 89 void pubble_sort(Node *head) 90 { 91 Node *end; 92 int t; 93 Node *p,*pre; 94 p=head; 95 //end~NULL為有序部分,將end置為尾結點 96 while(p->next)p=p->next; 97 end=p; 98 //每輪冒泡end左移一個結點,一直到head與end重合 99 while(head!=end){ 100 p=head; 101 while(p!=end){ 102 if(p->num>p->next->num){ 103 t=p->num; 104 p->num=p->next->num; 105 p->next->num=t; 106 } 107 pre=p; 108 p=p->next; 109 } 110 end=pre; 111 } 112 } 113 114 115 116 int main() 117 { 118 Node *head; 119 head=creat(); 120 121 pubble_sort(head); 122 123 print(head); 124 125 return 0; 126 }