Leetcode: Insertion Sort List

來源:互聯網
上載者:User

標籤: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 next10         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 in12         {13             pre = pre.next;14         }15         cur.next = pre.next;// plug in current node to the right place16         pre.next = cur;17         cur = next; //go on to deal with the next node in the unsorted list18     }19     return helper.next;20 }

 

Leetcode: Insertion Sort List

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.