链表排序

33 篇文章 0 订阅
8 篇文章 0 订阅

<p>对链表进行合并算法排序,基本思路和merge算法一下。</p><p>一下是Java实现:</p><div>
</div>
public class ListNode{
	int val;
	ListNode next;
	ListNode(int val){
		this(val, null);
	}
	ListNode(int val, ListNode next){
		this.val = val;
		this.next = next;
	}
}
public class Util{
	public static void printList(ListNode head){
		ListNode node = head;
		StringBuilder builder = new StringBuilder();
		while(node != null){
			builder.append(node.val + " ");
			node = node.next;
		}
		System.out.println(builder.toString().trim());
	}
}

public class MergeSortList{
	public static void main(String[] args){
		int[] arr = {1,3,3,1,3,1,3,3,2,3,2,2,1,1,2,3};
		ListNode head = null, tail = null;
		for(int i = 0; i < arr.length; i++){
			if(head == null) {
				head = new ListNode(arr[i]);
				tail = head;
			}
			else{
				tail.next = new ListNode(arr[i]);
				tail = tail.next;
			}
		}
		Util.printList(head);
		
		ListNode m = new MergeSortList().sort(head);
		Util.printList(m);
	}
	
	public ListNode sort(ListNode head){
		if(head == null || head.next == null) return head;
		
		ListNode hnode = head;
		ListNode lnode = split(hnode);
		hnode = sort(hnode);
		lnode = sort(lnode);
		ListNode m = merge(hnode, lnode);
		return m;
	}
	
	/**
	 * Merge to sorted list
	 * */
	public ListNode merge(ListNode alist, ListNode blist){
		if(alist == null) return blist;
		if(blist == null) return alist;
		
		ListNode rvl = null;
		ListNode tmp = null;
		if(alist.val <= blist.val){
			tmp = alist.next;
			rvl = alist;
			rvl.next = merge(tmp, blist);
		}else{
			tmp = blist.next;
			rvl = blist;
			rvl.next = merge(alist, tmp);
		}
		return rvl;
	}
	
	public ListNode split(ListNode head){
		ListNode fast;
		ListNode slow;
		if(null == head || null == head.next){
			return null;
		}
		
		slow = head;
		fast = head.next;
		while(fast != null){
			fast = fast.next;
			if(fast != null){
				slow = slow.next;
				fast = fast.next;
			}

		}
		ListNode low = slow.next;
		slow.next = null;
		return low;
	}
}

输出结果:

1 3 3 1 3 1 3 3 2 3 2 2 1 1 2 3
1 1 1 1 1 2 2 2 2 3 3 3 3 3 3 3

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值