面试中经常会碰到单链表的排序,主要是插入排序和归并排序
插入排序:
1 class Solution { 2 public: 3 ListNode *insertionSortList(ListNode *head) { 4 if (head == nullptr) return head; 5 if (head->next == nullptr) return head; 6 7 ListNode* dummy = new ListNode(-1); 8 dummy->next = head; 9 10 ListNode* cur = head->next; 11 ListNode* cur_pre = head; 12 while (cur) { 13 ListNode* cur_next = cur->next; 14 ListNode* p_pre = dummy; 15 ListNode* p = dummy->next; 16 while (cur->val >= p->val && p != cur) { 17 p_pre = p_pre->next; 18 p = p->next; 19 } 20 if (p == cur) { 21 cur_pre = cur; 22 cur = cur->next; 23 } else { 24 p_pre->next = cur; 25 cur->next = p; 26 cur_pre->next = cur_next; 27 cur = cur_next; 28 } 29 } 30 return dummy->next; 31 } 32 };
归并排序:
1 class Solution { 2 public: 3 ListNode *sortList(ListNode *head) { 4 if(head == nullptr || head->next == nullptr) return head; 5 ListNode* slow = head; 6 ListNode* fast = head->next; 7 8 while(fast && fast->next){ 9 slow = slow->next; 10 fast = fast->next->next; 11 } 12 ListNode* head2 = slow->next; 13 slow->next = nullptr; 14 ListNode* leftRes = sortList(head); 15 ListNode* rightRes = sortList(head2); 16 17 return merge(leftRes,rightRes); 18 19 } 20 21 ListNode* merge(ListNode* head1,ListNode* head2){ 22 ListNode* head = new ListNode(-1); 23 ListNode* p = head; 24 ListNode* p1 = head1; 25 ListNode* p2 = head2; 26 while(p1 && p2){ 27 if(p1->val <= p2->val){ 28 p->next = p1; 29 p1 = p1->next; 30 }else{ 31 p->next = p2; 32 p2 = p2->next; 33 } 34 p = p->next; 35 } 36 if(p1) p->next = p1; 37 if(p2) p->next = p2; 38 return head->next; 39 } 40 };