LeetCode 148. Sort List

参考了别人的题解,用了归并排序。


实现O(nlogn)复杂度的排序方法有归并、快排和堆排序。

有时间的话还应该去复习一下这三种方法实现以及复杂度的证明。


代码:

class Solution
{
public:
	ListNode* sortList(ListNode* head)
	{
		if (head == NULL || head->next==NULL)
		{
			return head;
		}

		ListNode* fast=head, *slow=head;
		for ( ; fast->next!=NULL&&fast->next->next!=NULL; fast=fast->next->next, slow=slow->next) {}
		fast = slow;
		slow = slow->next;
		fast->next = NULL;
		fast = sortList(head); // half before 
		slow = sortList(slow); // half after

		return merge(fast, slow);
	}

	ListNode* merge(ListNode* before, ListNode* after)
	{
		ListNode* head;
		if ( before->val < after->val )
		{
			head = before;
			before = before->next;
		} else
		{
			head = after;
			after = after->next;
		}

		ListNode* now = head;
		while ( before!=NULL && after!=NULL )
		{
			if (before->val < after->val)
			{
				now->next = before;
				before = before->next;
			} else
			{
				now->next = after;
				after = after->next;
			}
			now = now->next;			
		}
		if (before != NULL) { now->next = before; }
		if (after  != NULL) { now->next = after; }
		return head;
	}
};


你可能感兴趣的:(LeetCode,C++)