【Leetcode】Sort List

题目链接:https://leetcode.com/problems/sort-list/

题目:

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

思路:

用归并排序,难点在递归划分链表中点。本题解答参考了网络答案。

算法:

	public ListNode sortList(ListNode head) {
		if(head==null||head.next==null)
			return head;
		ListNode fast = head,slow = head,l2 = null;
		//fast走两步,slow走一步,当fast到达表尾时,slow在链表中间位置
		while(fast.next!=null&&fast.next.next!=null){
			slow = slow.next;
			fast = fast.next.next;
		}//此时fast在表尾,slow在中间
		l2 = slow.next; //第二条链表表头
		slow.next = null; //断开

		head = sortList(head);//分冶
		l2 = sortList(l2);
		
		return mergeTwoLists(l2, head);//合并
	}
	
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = null,l,p = l1,q = l2;
		//==确定头节点
		if(p!=null&&q!=null){
			if(p.val<q.val){
				head = p;
				p = p.next;
			}else{
				head = q;
				q = q.next;
			}
		}else if(p==null){
			head = q;
			return head;
		}else if(q==null){
			head = p;
			return head;
		}
		l = head; 
		//===end
		
		while(p!=null&&q!=null){
			if(p.val<q.val){
				l.next = p;
				l = p;
				p = p.next;
			}else{
				l.next = q;
				l = q;
				q = q.next;
			}
		}
		
		if(p==null){
			l.next = q;
		}else if(q==null){
			l.next = p;
		}
			
		return head;
    }


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yeqiuzs/article/details/49944151
个人分类: leetcode
所属专栏: Leetcode题解java版
上一篇【Leetcode】Reverse Nodes in k-Group
下一篇【Leetcode】Merge k Sorted Lists
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭