标签:style blog http color io div
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); } }
[leetcode] Insertion Sort List,布布扣,bubuko.com
[leetcode] Insertion Sort List
标签:style blog http color io div
原文地址:http://www.cnblogs.com/jdflyfly/p/3830452.html