【歸併排序】LeetCode - 148. Sort List

LeetCode - 148. Sort List

Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4

Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5

  要用常量空間,也就是不能新開一個鏈表,每個節點都new一個新的。O(NlogN)O(NlogN) 的時間,也就是要用 merge sort:

ListNode* merge(ListNode* p1, ListNode* p2) {
	ListNode *dummyHead = new ListNode(0), *cur = dummyHead;
	while (p1 && p2) {
		if (p1->val > p2->val) {
			cur->next = p2;
			p2 = p2->next;
		}
		else {
			cur->next = p1;
			p1 = p1->next;
		}
		cur = cur->next;
	}
	if (p1)	cur->next = p1;
	else    cur->next = p2;
	return dummyHead->next;
}

// 二分成一個或nullptr爲止
ListNode* sortList(ListNode* head) {
	if (head == nullptr || head->next == nullptr)
		return head;
	ListNode *p1 = head, *p2 = head->next;  // 快慢指針
	while (p2->next) {
		p1 = p1->next;
		p2 = p2->next;
		if (p2->next)
			p2 = p2->next;
	}
	p2 = p1->next;
	p1->next = nullptr;
	return merge(sortList(head), sortList(p2));
}

  值得注意的是,merge 之後,p1、p2 都很有可能變了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章