*/-->
pre.src {background-color: Black; color: White;}
pre.src {background-color: Black; color: White;}
leet code Sort List
对链表使用快慢指针归并排序
Sort List
Sort a linked list in O(n log n) time using constant space complexity.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* sortList(ListNode* head) { if (head == NULL || head->next == NULL) { return head; } ListNode *fast = head; ListNode *slow = head; while (fast->next != NULL && fast->next->next != NULL) { fast = fast->next->next; slow = slow->next; } // slow 指到中间,fast 直到了结尾 fast = slow; // 先保留 mid 的值 slow = slow->next; // 相当于 mid+1 fast->next = NULL; // 断掉链表 ListNode *l1 = sortList(head); ListNode *l2 = sortList(slow); return merge(l1, l2); } ListNode *merge(ListNode *l1, ListNode *l2) { // 合并链表 ListNode t(-1); ListNode *p = &t; while (l1 != NULL && l2 != NULL) { if (l1->val > l2->val) { p->next = l2; l2 = l2->next; p = p->next; } else { p->next = l1; l1 = l1->next; p = p->next; } } while (l1 != NULL) { p->next = l1; l1 = l1->next; p = p->next; } while (l2 != NULL) { p->next = l2; l2 = l2->next; p = p->next; } return t.next; // 注意返回 } };
时间: 2024-12-04 17:49:21