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

Insertion Sort List

时间:2016-07-03 01:43:18      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

Sort a linked list using insertion sort.

Example

Given 1->3->2->0->null, return 0->1->2->3->null.

分析:

利用insertion sort的原理,把list A的一个node插入到另一个list B里面,这里关键是list B的尾部的处理。

 1 /**
 2  * Definition for ListNode.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int val) {
 7  *         this.val = val;
 8  *         this.next = null;
 9  *     }
10  * }
11  */ 
12 public class Solution {
13     /**
14      * @param head: The first node of linked list.
15      * @return: The head of linked list.
16      * cnblogs.com/beiyeqingteng/
17      */
18      
19     public ListNode insertionSortList(ListNode head) {
20         if (head == null || head.next == null) return head;
21         ListNode dummyNode = new ListNode(Integer.MIN_VALUE);
22         
23         while(head != null) {
24             ListNode current = dummyNode;
25             while(head.val > current.val && current.next != null && current.next.val < head.val) {
26                 current = current.next;
27             }
28             ListNode remainingHead = current.next;
29             current.next = head;
30             head = head.next;
31             current.next.next = remainingHead;
32         }
33         return dummyNode.next;
34     }
35 }

转载请注明出处:cnblogs.com/beiyeqingteng/

Insertion Sort List

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5636402.html

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