码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] Insertion Sort List

时间:2014-07-08 00:41:08      阅读:228      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!