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

Insertion Sort List

时间:2015-08-09 12:23:50      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:

问题描述

Sort a linked list using insertion sort.

 

解决思路

1. 设置first和last指针;

2. 插入分三种情况。

 

程序

public class Solution {
    public ListNode insertionSortList(ListNode head) {
        ListNode dummy = new ListNode(-1);

        ListNode first = null, last = null;
        ListNode cur = head;
        
        while (cur != null) {
            ListNode next = cur.next; // save the next node
            cur.next = null;
            
            if (first == null || last == null) {
                dummy.next = cur;
                first = cur;
                last = cur;
            } else {
                if (cur.val <= first.val) {
                    // insert before the first
                    dummy.next = cur;
                    cur.next = first;
                    first = cur;
                } else if (cur.val >= last.val) {
                    // insert after last
                    last.next = cur;
                    last = cur;
                } else {
                    // find the insert place
                    ListNode node = first;
                    while (node.next != null) {
                        if (node.next.val > cur.val) {
                            break;
                        }
                        node = node.next;
                    }
                    ListNode tmp = node.next;
                    node.next = cur;
                    cur.next = tmp;
                }
            }
            
            cur = next;
        }

        return first;
    }
}

 

Insertion Sort List

标签:

原文地址:http://www.cnblogs.com/harrygogo/p/4714865.html

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