题目链接:https://leetcode.com/problems/sort-list/
/*题意:对链表进行排序*/ /** *思路:归并排序 * 分治:将链表分成两段:用slow和fast指针,slow每次只走一步,fast每次 * 走两步。当fast为空时,slow所在位置就是链表中间。 * 合并:两个简单的链表的合并 */ class Solution { public: void show(ListNode *head) { while(head != NULL) { cout << head->val << " "; head = head->next; } cout << endl; } ListNode *Merge(ListNode *headA, ListNode *headB) { ListNode *root = new ListNode(0); ListNode *p = root; while(headA && headB) { if(headA->val <= headB->val) { p->next = headA; headA = headA->next; } else { p->next = headB; headB = headB->next; } p = p->next; } while(headA) { p->next = headA; p = p->next; headA = headA->next; } while(headB) { p->next = headB; p = p->next; headB = headB->next; } ListNode *res = root->next; delete root; return res; } ListNode *MergeSort(ListNode *head) { //只有一个结点 if(head == NULL || head->next == NULL) return head; ListNode *slow = head; //慢指针 ListNode *fast = head->next->next;//快指针 while(fast != NULL && fast->next != NULL) { slow = slow->next; fast = fast->next->next; } ListNode *headA = head; ListNode *headB = slow->next; slow->next = NULL; //将链表断开 headA = MergeSort(headA); headB = MergeSort(headB); return Merge(headA, headB); } ListNode* sortList(ListNode* head) { if(head == NULL || head->next == NULL) return head; return MergeSort(head); } };
时间: 2024-10-19 06:12:33