Sort List

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

The tricky point of this problem is that these number stored in a linked list instead of an array. We could use merge sort for this problem. We need to seperate the list into two part and cut the link between them. Then recursively sort them and merge them together.

The merge algorithm is also a bit complicated since it's a linked list. In this implementation, we need to maintain two list. In the comparison of two nodes in list1 and list2. If 1 < 2, we continue to the next node of list1, else we would swap list2 up to become the next node of list and swap list1 down.

public class Solution {
	public static ListNode sortList(ListNode head) {
		if(head == null) return null;
		if(head.next == null) return head;
		ListNode start = head;
		while(head.next != null)
		{
			head = head.next;
		}
		ListNode end = head;
		ListNode a = mergeSort(start, end);
        return a;
	}
    public static ListNode mergeSort(ListNode start, ListNode end)
    {
		if(start == end) return start;
		if(start.next == end)
		{
			if(start.val > end.val)
			{
				int temp = start.val;
				start.val = end.val;
				end.val = temp;
				return start;
			}
			else return start;
		}
		ListNode node1 = start;
		ListNode node2 = start;
		while(node2 != end && node2.next != end)
		{
			node1 = node1.next;
			node2 = node2.next.next;
		}
		ListNode middleNext = node1.next;
		node1.next = null;
		node1 = mergeSort(start, node1);
		node2 = mergeSort(middleNext, end);
		ListNode b = merge(node1, node2);
    	return b;
    }
    public static ListNode merge(ListNode list1, ListNode list2) 
    {
    	  if (list1 == null) return list2;
    	  if (list2 == null) return list1;

    	  ListNode head;
    	  if (list1.val < list2.val) 
    	  {
    	    head = list1;
    	  } else {
    	    head = list2;
    	    list2 = list1;
    	    list1 = head;
    	  }
    	  while(list1.next != null && list2 != null) {
    	    if (list1.next.val <= list2.val) {
    	      list1 = list1.next;
    	    } else {
    	      ListNode tmp = list1.next;
    	      list1.next = list2;
    	      list2 = tmp;
    	      list1 = list1.next;
    	    }
    	  } 
    	  if (list1.next == null) list1.next = list2;
    	  return head;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值