链表插入排序 lintcode

 链表插入排序
难度系数 容易 通过率 31%

用插入排序对链表排序

样例

Given 1->3->2->0->null, return 0->1->2->3->null

package tju.cs.bigdata.chc;


public class ListNode {
	int val;
	ListNode next;

	ListNode(int val) {
		this.val = val;
		this.next = null;
	}
	
	public ListNode createList(String s){
		ListNode res = new ListNode(-1);
		String[] strings = s.split("->");
		ListNode cur = res;
		for(String st : strings){
			if(!st.equals("null"))cur.next = new ListNode(Integer.parseInt(st));
			cur = cur.next;
		}
		
		return res.next;
	}
	public void printList(ListNode l){
		ListNode cur = l;
		if(l == null)return;
		while(cur != null){
			System.out.print(cur.val + " ");
			cur = cur.next;
		}
	}
}

package tju.cs.bigdata.chc;


public class InsertionSortList {
	   public ListNode insertionSortList(ListNode head) {
	        // write your code here
	        if(head == null || head.next == null){
	            return head;
	        }
	        ListNode res = new ListNode(-1);
	        ListNode cur = head;
	        ListNode curtmp = res;
	        while(cur != null){
	            curtmp = res;
	            
	            while(curtmp.next != null && curtmp.next.val <= cur.val){
	                curtmp = curtmp.next;
	            }
//	            curtmp.printList(curtmp);
//	            cur.printList(cur);
	            ListNode l = cur.next;
	            cur.next = curtmp.next;
	            curtmp.next = cur;
	            cur = l;
//	            if(cur != null)cur.printList(cur);
//	            curtmp.printList(curtmp);
	        }        
	        return res.next;
	        
	    }
	   public static void main(String[] args){
		   String string = "1->3->2->0->null";
		   ListNode res = new ListNode(-1).createList(string);
		   res.printList(res);
		   InsertionSortList insertionSortList = new InsertionSortList();
		   ListNode res1 = insertionSortList.insertionSortList(res);
		   res1.printList(res1);
	   }
}	


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值