用归并法进行单链表排序
1 struct ListNode { 2 int val; 3 ListNode *next; 4 ListNode(int x) : val(x), next(nullptr) {} 5 }; 6 7 ListNode* median(ListNode *head) 8 { 9 if(head != nullptr && head->next != nullptr) 10 { 11 ListNode *m = head; 12 ListNode *last = m->next; 13 while(last->next != nullptr) 14 { 15 if((last = last->next) != nullptr) last = last->next; 16 else break; 17 m = m->next; 18 } 19 return m; 20 } 21 else return head; 22 } 23 24 ListNode* advance_aux(ListNode *head, int len) 25 { 26 while(--len > 0) head = head->next; 27 return head; 28 } 29 30 ListNode** merge_aux(ListNode **l_head, ListNode **r_head, int l_len, int r_len) 31 { 32 cout<<"merge " 33 <<(*l_head)->val<<' '<<l_len<<" and " 34 <<(*r_head)->val<<' '<<r_len<<'\n'; 35 ListNode **left = l_head, **right = r_head; 36 while(l_len != 0 && r_len != 0) 37 { 38 while(r_len != 0 && (*right)->val < (*left)->val) 39 { 40 right = &(*right)->next; 41 --r_len; 42 } 43 if(*right == *r_head) 44 { 45 while(l_len != 0 && (*left)->val <= (*right)->val) 46 { 47 left = &(*left)->next; 48 --l_len; 49 } 50 } 51 else 52 { 53 cout<<"\tmove [" 54 <<(*r_head)->val<<"," 55 <<(r_len ? (*right)->val : -1) 56 <<") before " 57 <<(*left)->val<<"\n"; 58 ListNode *tmp = *left; 59 *left = *r_head; 60 *r_head = *right; 61 *right = tmp; 62 left = &tmp->next; 63 --l_len; 64 right = r_head; 65 } 66 } 67 while(r_len-- != 0) 68 { 69 ListNode *tmp = *left; 70 *left = *r_head; 71 *r_head = *right; 72 *right = tmp; 73 } 74 return l_head; 75 } 76 77 ListNode** insertionSortList_aux(ListNode **head, int len) 78 { 79 cout<<"deal "<<(*head)->val<<' '<<len<<'\n'; 80 if(len > 2) 81 { 82 int left_len = len/2, right_len = len - left_len; 83 head = insertionSortList_aux(head, left_len); 84 ListNode *left_last = advance_aux(*head, left_len); 85 ListNode **right_head = insertionSortList_aux(&left_last->next, right_len); 86 head = merge_aux(head, right_head, left_len, right_len); 87 } 88 else if(len == 2) 89 { 90 if((*head)->val > (*head)->next->val) 91 { 92 int tmp = (*head)->val; 93 (*head)->val = (*head)->next->val; 94 (*head)->next->val = tmp; 95 } 96 } 97 return head; 98 } 99 100 ListNode* insertionSortList(ListNode *head) 101 { 102 int len = 0; 103 ListNode *last = head; 104 while(last != nullptr) 105 { 106 ++len; 107 last = last->next; 108 } 109 insertionSortList_aux(&head, len); 110 return head; 111 } 112 113 ListNode* insertNode(ListNode *head, int i) 114 { 115 auto p = new ListNode{i}; 116 p->next = head; 117 return p; 118 } 119 120 int main() 121 { 122 ListNode *p = nullptr; 123 p = insertNode(p, 0); 124 p = insertNode(p, 0); 125 p = insertNode(p, 0); 126 p = insertNode(p, 0); 127 for(ListNode *i = p; i != nullptr; i = i->next) cout<<i->val<<" "; 128 cout<<endl; 129 p = insertionSortList(p); 130 for(ListNode *i = p; i != nullptr; i = i->next) cout<<i->val<<" "; 131 cout<<endl; 132 while(p != nullptr) 133 { 134 ListNode *tmp = p->next; 135 delete p; 136 p = tmp; 137 } 138 }