码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode--Sort List

时间:2015-01-15 16:01:52      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:leetcode   linklist   mergesort   归并排序   

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

MergeSort对于链表的排序,实现了就地排序的同时,时间复杂度和空间复杂度都达到了基于比较的排序的最优值,因此归并排序是链表排序的最佳排序方式。

/**
 * 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* temp = head->next;
		int n = 0;
		while(temp!=NULL)
		{
			n++;
			temp = temp->next;
		}
		for(int i=1; i<n; i*=2)
		{
			ListNode* pre = head;
			ListNode* low = pre->next;
			while(low!=NULL)
			{
				ListNode* mid = low;
				for(int j=1;j<i;j++)
				{
					//说明当前剩余需要归并的元素少于所需元素,直接退出;
					if(mid==NULL)
						break;
					mid = mid->next;
				}
				//说明当前剩余需要归并的元素少于所需元素,直接退出;
				if(mid == NULL || mid->next == NULL)
					break;
				ListNode* end = mid->next;
				for(int j=1;j<i;j++)
				{
					if(end->next==NULL)
						break;
					end = end->next;
				}	
				merge(pre,low,mid,end);
				low = pre->next;
				for(int j=1; j<=2*i; j++)
				{
					if(low == NULL)
						break;
					pre = low;
					low = low->next;
				}
			}
		}
		temp = head->next;
		ListNode* save;
		while(temp!=NULL && head->val > temp->val)
		{
			save = temp;
			temp = temp->next;
		}
		if(temp != head->next)
		{
			ListNode* temp_head = head->next;
			head->next = temp;
			save->next = head;
			head = temp_head;
		}
		return head;		
	}
	void merge(ListNode* pre, ListNode* low, ListNode* mid, ListNode* end)
	{
		ListNode* end1 = mid->next;
		ListNode* low2 = mid->next;
		ListNode* t_pre = pre;
		ListNode* end2 = end->next;
		while(low!=end1 || low2!=end2)
		{
			if(low == end1)
			{
				t_pre->next = low2;
				low2 = low2->next;
			}
			else if(low2 == end2)
			{
				t_pre->next = low;
				low = low->next;
			}
			else if(low->val > low2->val)
			{
				t_pre->next = low2;
				low2 = low2->next;
			}
			else
			{
				t_pre->next = low;
				low = low->next;
			}
			t_pre = t_pre->next;
		}
		t_pre->next = end2;
	}
};


LeetCode--Sort List

标签:leetcode   linklist   mergesort   归并排序   

原文地址:http://blog.csdn.net/shaya118/article/details/42742297

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!