解决思路
这个道题就像排队,先找个排头dummy
,然后依次从head
节点放入dummy
,只需要依次dummy
现有节点比较,插入其中!
原来是因为我们每次都要从头比较,但是测试集很多都是顺序排列的,没必要从头开始,我们直接比较最后一个tail
,放在后面!
class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode dummy = new ListNode(Integer.MIN_VALUE);
ListNode pre = dummy;
ListNode tail = dummy;
ListNode cur = head;
while (cur != null) {
if (tail.val < cur.val) {
tail.next = cur;
tail = cur;
cur = cur.next;
} else {
ListNode tmp = cur.next;
tail.next = tmp;
while (pre.next != null && pre.next.val < cur.val) pre = pre.next;
cur.next = pre.next;
pre.next = cur;
pre = dummy;
cur = tmp;
}
}
return dummy.next;
}
}