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

[LeetCode]147 Insertion Sort List

时间:2015-01-09 01:50:04      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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

http://blog.csdn.net/linhuanmars/article/details/21144553

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode insertionSortList(ListNode head)
    {
        if (head == null || head.next == null)
            return head;

        // Add dummy head
        ListNode dummyhead = new ListNode(0);

        ListNode pre;
        ListNode cur = head;
        
        while(cur!=null)
        {
            ListNode next = cur.next;
            pre = dummyhead;
            while(pre.next!=null && pre.next.val<=cur.val)
                pre = pre.next;
            
            cur.next = pre.next;
            pre.next = cur;
            cur = next;
        }
        return dummyhead.next;
    }
}


[LeetCode]147 Insertion Sort List

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1600822

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