Insertion Sort List

问题描述

Sort a linked list using insertion sort.

解决思路

1. 设置first和last指针;

2. 插入分三种情况。

程序

public class Solution {
    public ListNode insertionSortList(ListNode head) {
        ListNode dummy = new ListNode(-1);

        ListNode first = null, last = null;
        ListNode cur = head;
        
        while (cur != null) {
            ListNode next = cur.next; // save the next node
            cur.next = null;
            
            if (first == null || last == null) {
                dummy.next = cur;
                first = cur;
                last = cur;
            } else {
                if (cur.val <= first.val) {
                    // insert before the first
                    dummy.next = cur;
                    cur.next = first;
                    first = cur;
                } else if (cur.val >= last.val) {
                    // insert after last
                    last.next = cur;
                    last = cur;
                } else {
                    // find the insert place
                    ListNode node = first;
                    while (node.next != null) {
                        if (node.next.val > cur.val) {
                            break;
                        }
                        node = node.next;
                    }
                    ListNode tmp = node.next;
                    node.next = cur;
                    cur.next = tmp;
                }
            }
            
            cur = next;
        }

        return first;
    }
}
原文地址:https://www.cnblogs.com/harrygogo/p/4714865.html