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

Insertion Sort List

时间:2015-03-14 13:43:02      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

Insertion Sort List

问题:

Sort a linked list using insertion sort.

思路:

  三行情书 旧旧 新 旧 旧 新

我的代码:

技术分享
/**
 * 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;
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode tail = head;
        ListNode cur = head.next;
        while(cur != null)
        {
            if(cur.val >= tail.val)
            {
                cur = cur.next;
                tail = tail.next;
            }
            else
            {
                ListNode first = dummy.next;
                ListNode pre = dummy;
                while(cur.val > first.val)
                {
                    first = first.next;
                    pre = pre.next;
                }
                tail.next = cur.next;
                cur.next = pre.next;
                pre.next = cur;
                cur = tail.next;
            }
        }
        return dummy.next;
    }
}
View Code

 

Insertion Sort List

标签:

原文地址:http://www.cnblogs.com/sunshisonghit/p/4337393.html

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