147. Insertion Sort List(使用插入排序对链表进行排序)

313 阅读1分钟

描述

使用插入排序对链表进行排序

思路

见插入排序

实现

 public ListNode insertionSortList(ListNode head) {
        if (head == null || head.next == null) return head;

        ListNode tmp = head.next;
        ListNode pre = head;
        // 从第二个节点开始
        int index = 2;
        while (tmp != null) {

            int index2 = findIndex(head, tmp);
            // 1 3(pre) 2(tmp) 4 需要移动
            if (index2 < index) {
                pre.next = tmp.next;
                head = insertList(head, index2, tmp);
                tmp = pre.next;
            }
            // 1 2(pre) 3(tmp) 4 无需移动
            else {
                pre = tmp;
                tmp = tmp.next;
            }
            index++;

        }
        return  head;

    }

    int findIndex(ListNode head, ListNode listNode) {
        int index = 1;
        while (head.val < listNode.val ) {
            head = head.next;
            index++;
        }

        return index;

    }

    ListNode insertList(ListNode head, int index, ListNode insert) {
        if (index == 1) {
            insert.next = head;
            return insert;
        }
        ListNode tmp = head;
        index = index - 2;
        while (index > 0) {
            tmp = tmp.next;
            index--;
        }
        insert.next = tmp.next;
        tmp.next = insert;
        return head;

    }