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

leetcode_Sort List

时间:2015-08-12 11:38:22      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:

描述:

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

思路:

1.链表的排序一般每遇到过,让用O(nlogn)解决该问题就更不知如何下手了

2.通过参考网上的思路才知道用归并排序,采用递归的方法解决该问题还是可以的,就是理解起来有点费劲

3.重要步骤:递归,归并,查找数组有效范围内的中间节点,有序数组合并

代码:

 public ListNode sortList(ListNode head)
	{
		if(head==null||head.next==null)
			return head;
		ListNode midNode=getMidNode(head);
		ListNode newHead=midNode.next;
		midNode.next=null;
		head=mergeLists(sortList(newHead), sortList(head));
		return head;
	}

	public ListNode mergeLists(ListNode head1, ListNode head2)
	{
		if(head1==null&&head2==null)
			return head1;
		if(head1==null)
			return head2;
		if(head2==null)
			return head1;
		ListNode newHead=new ListNode(-1);
		ListNode curListNode=newHead;
		while(head1!=null&&head2!=null)
		{
			if(head1.val<head2.val)
			{
				curListNode.next=head1;
				head1=head1.next;
			}else 
			{
				curListNode.next=head2;
				head2=head2.next;
			}
			curListNode=curListNode.next;
		}
		if(head1!=null)curListNode.next=head1;
		if(head2!=null)curListNode.next=head2;
		return newHead.next;
	}

	public ListNode getMidNode(ListNode head)
	{
		if(head==null||head.next==null)
			return head;
		ListNode p=head,q=head;
		while(q.next!=null&&q.next.next!=null)
		{
			p=p.next;
			q=q.next.next;
			
		}
		return p;
	}


版权声明:本文为博主原创文章,未经博主允许不得转载。

leetcode_Sort List

标签:

原文地址:http://blog.csdn.net/mnmlist/article/details/47440479

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