您的位置:首页 > 其它

Insertion Sort List

2014-05-21 23:57 411 查看
一道值得做的题,需要机智的自己定义一个头结点。

Java code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode insertionSortList(ListNode head) {
    	//逻辑短路
    	if(head == null || head.next == null){
    		return head;
    	}
    	ListNode headPtr = new ListNode(0);
    	headPtr.next = head;
        ListNode curNode = head.next;
        ListNode sortedEnd = head;
        while(curNode != null){
        	ListNode preTmp = headPtr;
        	ListNode tmp = headPtr.next; // Warning!! Not "ListNode tmp = head;" !!
        	//remove deplicate value
            while(curNode.val > tmp.val && tmp != curNode){
    			preTmp = tmp;
    			tmp = tmp.next;
        	}
        	if(curNode != tmp){
        		ListNode curNext = curNode.next;
        		preTmp.next = curNode;
        		curNode.next = tmp;
        		sortedEnd.next = curNext;
        		curNode = curNext;
        	}else{
        		sortedEnd = curNode;
        		curNode = curNode.next;
        	}
        }
    	return headPtr.next;
    }	
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: