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

Leetcode: Insertion Sort List

时间:2014-09-17 13:30:42      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   使用   for   div   sp   log   

Sort a linked list using insertion sort.

难度:84. 我自己的做法是使用了额外的空间,建立了一个新的sorted的LinkedList, 技巧还是建立一个dummy node做前置节点。

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13         public ListNode insertionSortList(ListNode head) {
14         if(head == null)
15             return null;
16         ListNode helper = new ListNode(0);
17         ListNode pre = helper;
18         ListNode cur = head;
19         while(cur!=null)
20         {
21             ListNode next = cur.next;
22             pre = helper;
23             while(pre.next!=null && pre.next.val<=cur.val)
24             {
25                 pre = pre.next;
26             }
27             cur.next = pre.next;
28             pre.next = cur;
29             cur = next;
30         }
31         return helper.next;
32       }
33 }

然后网上看到别人不用建立一个新的LinkedList, 直接在原来的LinkedList上面完成sort(我之前想过,但是一想到这样会有可能把遍历顺序搞乱,所以作罢,想到建立一个新的LinkedList),这个人记录了当前节点的下一跳的位置,然后把当前节点加入到已经sorted的list里面,不会影响。好赞的做法

难度:93

 1 public ListNode insertionSortList(ListNode head) {
 2     if(head == null)
 3         return null;
 4     ListNode helper = new ListNode(0);//helper is the dummy head for the result sorted LinkedList
 5     ListNode pre = helper; //pre is the pointer to find the suitable place to plug in the current node
 6     ListNode cur = head; //cur is current node, the node to be plugged in the sorted list
 7     while(cur!=null)
 8     {
 9         ListNode next = cur.next; //keep a record of the current node‘s next
10         pre = helper;
11         while(pre.next!=null && pre.next.val<=cur.val) //use pre to traverse the sorted list to find the suitable place to plug in
12         {
13             pre = pre.next;
14         }
15         cur.next = pre.next;// plug in current node to the right place
16         pre.next = cur;
17         cur = next; //go on to deal with the next node in the unsorted list
18     }
19     return helper.next;
20 }

 

Leetcode: Insertion Sort List

标签:style   blog   color   io   使用   for   div   sp   log   

原文地址:http://www.cnblogs.com/EdwardLiu/p/3976821.html

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