Insertion Sort List

来源:互联网 发布:棉拖鞋淘宝 编辑:程序博客网 时间:2024/06/10 10:06

一道值得做的题,需要机智的自己定义一个头结点。

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;    }}

0 0