[LeetCode] 147. 对链表进行插入排序

中等题,别看挺简单,能很快写出来代码蛮难的,后面可以用作面试考察题

大致思路遍历链表,对于每一次遍历i,将当前节点从链表上摘除,然后从链表开头到i节点:[head,i),寻找可以插入的位置。注意要处理边界情况:1. 可能插在了当前head节点前面 2. 当i节点的val比[head,i)中所有节点都大时,要插在了i的前面,此时注意更新i的pre节点

虽然是1A过的,但是调试也花了不少时间

public ListNode insertionSortList(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode i = head.next;
        ListNode pre = head;

        while (i!=null) {
            pre.next = i.next;

            ListNode tmp = head;
            ListNode tmpPre = null;
            while (tmp != pre.next) {
                if (i.val <= tmp.val) {
                    if (tmpPre == null) {
                        head = i;
                    } else {
                        tmpPre.next = i;
                    }
                    i.next = tmp;
                    break;
                } else {
                    tmpPre = tmp;
                    tmp = tmp.next;
                }
            }
            if (i.val > pre.val) {
                i.next = pre.next;
                pre.next = i;
                pre = pre.next;
            }

            i = pre.next;
        }

        return head;
    }
posted @ 2021-06-07 00:00  ACBingo  阅读(33)  评论(0编辑  收藏  举报