[leetcode] Sort List

題目:

Sort List

 Total Accepted: 9356 Total Submissions: 47695My Submissions

Sort a linked list in O(n log n) time using constant space complexity.

Have you been asked this question in an interview? 


class Solution {
public:
	ListNode *sortList(ListNode *head)
	{
		if (head == NULL || head->next == NULL) return head;
		//第一步:從中間分開鏈表(使用快慢指針)
		ListNode * fast_p = head, *slow_p = head;
		while (fast_p->next != NULL && fast_p->next->next != NULL)
		{
			fast_p = fast_p->next->next;
			slow_p = slow_p->next;
		}
		//第二步:分別對兩段鏈表排序(遞歸)
		ListNode * list1 = head;
		ListNode * list2 = slow_p->next; slow_p->next = NULL;
		list1 = sortList(list1);
		list2 = sortList(list2);
		//第三步:合併
		return merge(list1, list2);
	}
	ListNode * merge(ListNode * list1, ListNode * list2)
	{//合併兩個已經排序的List
		if (list1 == NULL) return list2;
		if (list2 == NULL) return list1;
		ListNode dummy(-1);//小技巧
		ListNode * current = &dummy;
		while (list1 != NULL && list2 != NULL)
		{
			if (list1->val < list2->val)//每次從List1和List2中選擇小的
			{
				current->next = list1; list1 = list1->next; current = current->next;
			}
			else
			{
				current->next = list2; list2 = list2->next; current = current->next;
			}
		}
		if (list1 != NULL)//如果List1還有節點
			current->next = list1;
		if (list2 != NULL)
			current->next = list2;

		return dummy.next;
	}
};


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