leetcode之时间复杂度为O(nlogn)的链表排序

3. Sort List

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

使用归并排序的思想,代码如下:

/**
 * Sort a linked list in O(n log n) time using constant space complexity.
 */
package com.leetcode.program;

import java.util.Random;

public class SortLinkedList {

	public ListNode sortList(ListNode head)
	{
		if(head == null || head.next == null)
			return head;
		ListNode midNode = findMiddleNode(head);
		if(midNode == null)
			return null;
		ListNode mid = midNode.next;
		midNode.next = null;
		ListNode h1 = sortList(head);
		ListNode h2 = sortList(mid);
		
		return mergeListNode(h1, h2);
//		return null;
	}
	
	private ListNode mergeListNode(ListNode h1, ListNode h2)
	{
		ListNode hret = (h1 == null) ? h2 : h1;
		if(hret == null)
			return hret;
		hret = (h1.val < h2.val) ? h1 : h2;
		if(hret == h1)
			h1 = h1.next;
		else
			h2 = h2.next;
		ListNode lashRet = hret;//the lash node of the returned List
		while(h1 != null && h2 != null)
		{
			if(h1.val < h2.val)
			{
				lashRet.next = h1;
				lashRet = h1;
				h1 = h1.next;
			}else{
				lashRet.next = h2;
				lashRet = h2;
				h2 = h2.next;
			}
		}
		if(h1 != null)
			lashRet.next = h1;
		if(h2 != null)
			lashRet.next = h2;
		return hret;
	}
	/*寻找链表的中间节点*/
	private ListNode findMiddleNode(ListNode h)
	{
		if(null == h || h.next == null)
			return h;
		ListNode midNode = h;
		while(h != null && h.next != null && h.next.next != null)
		{
			h = h.next.next;
			midNode = midNode.next;
		}
		return midNode;
	}
	public static void main(String[] args) {
		
		Random rand = new Random();
		ListNode head = null;
		ListNode currentNode = null;
		for(int i = 0 ; i < 10; i ++)
		{
			if(head == null)
			{
				head = new ListNode(rand.nextInt(47));
				currentNode = head;
			}else{
				currentNode.next = new ListNode(rand.nextInt(47));
				currentNode = currentNode.next;
			}
		}
		
		SortLinkedList s = new SortLinkedList();
		ListNode mid = s.findMiddleNode(head);
		System.out.println(mid.val);
		ListNode hret = s.sortList(head);
		while(hret != null)
		{
			System.out.print(hret.val + " ");
			hret = hret.next;
		}
//		while(head != null)
//		{
//			System.out.print(head.val + " ");
//			head = head.next;
//		}
	}

}

class ListNode{
	int val;
	ListNode next;
	ListNode(int x){
		val = x;
		next = null;
	}
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值