leetcode 148. 排序链表(Sort List)

在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。

示例 1:

输入: 4->2->1->3
输出: 1->2->3->4

示例 2:

输入: -1->5->3->4->0
输出: -1->0->3->4->5

 

原题链接

 

 

思路:

 利用快慢指针来找到归并需要的中点,然后和数组的归并排序做法相似,一直递归到低层,然后合并

 

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode sortList(ListNode head) {
        if(head == null || head.next == null)
        	return head;
        ListNode pre = null, slow = head, fast = head;//fast=head.next报错,why
        while(fast!=null && fast.next!=null)
        {
        	pre = slow;
        	fast = fast.next.next;
        	slow = slow.next;
        }
        pre.next = null;
        ListNode left = sortList(head);
        ListNode right = sortList(slow);
        return merge(left,right);
    }
	
	private ListNode merge(ListNode left, ListNode right) {
		ListNode dummyHead = new ListNode(-1);
		ListNode p = dummyHead;
		while(left!=null && right!=null)
		{
			if(left.val < right.val)
			{
				p.next = new ListNode(left.val);
				p = p.next;
				left = left.next;
			}
			else
			{
				p.next = new ListNode(right.val);
				p = p.next;
				right = right.next;				
			}
		}
		if(left!=null)
		{
			p.next = left;
		}
		if(right!=null)
		{
			p.next = right;
		}
		
		
		return dummyHead.next;
	}

}

 

你可能感兴趣的:(算法,面试,leetcode)