首页 > 代码库 > [leetcode] Insertion Sort List

[leetcode] Insertion Sort List

Sort a linked list using insertion sort.

https://oj.leetcode.com/problems/insertion-sort-list/

 

思路:模拟插入排序,因为没有pre的指针,所以找位置是从前向后找的。

 

public class Solution {    public ListNode insertionSortList(ListNode head) {        if (head == null || head.next == null)            return head;        ListNode newHead = new ListNode(-1);        newHead.next = head;        ListNode cur = head.next;        ListNode pre = head;        while (cur != null) {            ListNode next = cur.next;            ListNode p = newHead;            while (p.next != null && p.next.val < cur.val)                p = p.next;            pre.next = next;            cur.next = p.next;            p.next = cur;            if (p == pre)                pre = pre.next;            cur = next;        }        return newHead.next;    }    public static void main(String[] args) {        ListNode head = ListUtils.makeList(new int[] { 1, 3, 5, 6, 4 });        ListUtils.printList(head);        head = new Solution().insertionSortList(head);        ListUtils.printList(head);    }}