image.png

解决思路

这个道题就像排队,先找个排头dummy,然后依次从head节点放入dummy,只需要依次dummy现有节点比较,插入其中!
原来是因为我们每次都要从头比较,但是测试集很多都是顺序排列的,没必要从头开始,我们直接比较最后一个tail,放在后面!

  1. class Solution {
  2. public ListNode insertionSortList(ListNode head) {
  3. ListNode dummy = new ListNode(Integer.MIN_VALUE);
  4. ListNode pre = dummy;
  5. ListNode tail = dummy;
  6. ListNode cur = head;
  7. while (cur != null) {
  8. if (tail.val < cur.val) {
  9. tail.next = cur;
  10. tail = cur;
  11. cur = cur.next;
  12. } else {
  13. ListNode tmp = cur.next;
  14. tail.next = tmp;
  15. while (pre.next != null && pre.next.val < cur.val) pre = pre.next;
  16. cur.next = pre.next;
  17. pre.next = cur;
  18. pre = dummy;
  19. cur = tmp;
  20. }
  21. }
  22. return dummy.next;
  23. }
  24. }