Insertion Sort List

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);  // a new list
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 next = current.next;
29             current.next = head;
30             head = head.next;
31             current.next.next = next;
32         }
33         return dummyNode.next;
34     }
35 }

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

posted @ 2016-07-03 00:37  北叶青藤  阅读(129)  评论(0编辑  收藏  举报