题目描述
Sort a linked list using insertion sort.
https://upload.wikimedia.org/wikipedia/commons/0/0f/Insertion-sort-example-300px.gif
方法思路
创建一个辅助的新链表,并且使用一个指针遍历原链表,每次将原链表中的一个节点插入到新链表的合适位置(即该节点的值大于新链表上的节点的值,又小于后一节点的值)。最后将新链表的头部返回即可。
class Solution {
//Runtime: 32 ms, faster than 34.04%
//Memory Usage: 37.9 MB, less than 54.32%
//关键在于创建一个辅助链表
public ListNode insertionSortList(ListNode head) {
//边界情况判定
if( head == null || head.next == null)
return head;
ListNode helper = new ListNode(0); //新建一个辅助链表
ListNode cur = head; //the node will be inserted
ListNode pre = helper; //insert node between pre and pre.next
ListNode next = null;
//the next node will be inserted
//not the end of input list
while( cur != null ){
next = cur.next;
//find the right place to insert
while( pre.next != null && pre.next.val < cur.val ){
pre = pre.next;
}
//insert between pre and pre.next
cur.next = pre.next;//顺序不能乱
pre.next = cur;
pre = helper;//每次循环前重置pre为头结点,这样保证每次都从头往后遍历
cur = next;// cur指针后移一位,进入下一次排序
}
return helper.next;
}
}
没有注释的版本:
class Solution{
public ListNode insertionSortList(ListNode head){
if( head == null || head.next == null)
return head;
ListNode helper = new ListNode(0);
ListNode pre = helper, cur = head, next = null;
while(cur != null){
next = cur.next;
while(pre.next != null && pre.next.val < cur.val)
pre = pre.next;
cur.next = pre.next;
pre.next = cur;
pre = helper;
cur = next;
}
return pre.next;
}
}