LeetCode——对链表进行插入排序

Q:使用插入排序对链表进行排序。
A:
创建头结点;

    public ListNode insertionSortList(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode head0 = new ListNode(Integer.MIN_VALUE);
        ListNode node1 = head;
        ListNode node2 = head;
        ListNode tempNode = head0;
        boolean flag = false;
        while (node1 != null) {
            while (tempNode.next != null) {
                if (tempNode.next.val > node1.val) {
                    flag = true;
                    node2 = node1.next;
                    node1.next = tempNode.next;
                    tempNode.next = node1;
                    tempNode = tempNode.next;
                    break;
                }
                tempNode = tempNode.next;
            }
            if(!flag){
                node2 = node1.next;
                node1.next = tempNode.next;
                tempNode.next = node1;
            }
            flag = false;
            tempNode = head0;
            node1 = node2;
        }
        return head0.next;
    }
posted @ 2020-03-07 17:11  Shaw_喆宇  阅读(100)  评论(0编辑  收藏  举报