Leetcode: Insertion Sort List
2014-09-17 12:12
435 查看
Sort a linked list using insertion sort.
我原本的想法是用额外的空间拷贝每一个节点,建立了一个新的sorted的LinkedList, 后来看到别人的做法不用建立新的LinkedList, 直接以原有List上的节点组成新的sorted的LinkedList。我之前想这样做会扰乱遍历的顺序,但是其实sorted的list和unsorted list是完全分开互不影响的。先还是给sorted list建立一个dummy node做前置节点, 每次取unsorted list里面的一个节点,记录下下一跳位置,然后把这个点插入到sorted list对应位置上(pre.next指到null或者pre.next。val更大)。
Insert Sort的做法相当于是每次从原来的List里面删除头节点,再把这个头节点插入到新的List里相应的位置。这个新List全由原来的节点组成,只是变换了顺序。
时间复杂度是插入排序算法的O(n^2),空间复杂度是O(1)。
第二遍做法:
public class Solution { public ListNode insertionSortList(ListNode head) { ListNode dummy = new ListNode(-1); ListNode cursor = dummy; while (head != null) { ListNode next = head.next; while (cursor.next!=null && cursor.next.val<=head.val) { cursor = cursor.next; } head.next = cursor.next; cursor.next = head; head = next; cursor = dummy; } return dummy.next; } }
第一遍做法:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode insertionSortList(ListNode head) { if(head == null) return null; ListNode helper = new ListNode(0); ListNode pre = helper; ListNode cur = head; while(cur!=null) { ListNode next = cur.next; pre = helper; while(pre.next!=null && pre.next.val<=cur.val) { pre = pre.next; } cur.next = pre.next; pre.next = cur; cur = next; } return helper.next; } }
上面程序注释如下:
public ListNode insertionSortList(ListNode head) { if(head == null) return null; ListNode helper = new ListNode(0);//helper is the dummy head for the result sorted LinkedList ListNode pre = helper; //pre is the pointer to find the suitable place to plug in the current node ListNode cur = head; //cur is current node, the node to be plugged in the sorted list while(cur!=null) { ListNode next = cur.next; //keep a record of the current node's next pre = helper; //after one search, put pre back to its original place while(pre.next!=null && pre.next.val<=cur.val) //use pre to traverse the sorted list to find the suitable place to plug in { pre = pre.next; } cur.next = pre.next;// plug in current node to the right place pre.next = cur; cur = next; //go on to deal with the next node in the unsorted list } return helper.next; }
相关文章推荐
- Leetcode: Insertion Sort List
- [leetcode]Insertion Sort List
- [Leetcode][python]Insertion Sort List
- leetcode--Insertion Sort List
- leetcode:Insertion Sort List
- LeetCode:Insertion Sort List
- leetcode 133: Insertion Sort List
- LeetCode---Insertion Sort List
- 【LeetCode】-Insertion Sort List
- LeetCode Insertion Sort List
- Insertion Sort List (LeetCode)
- [Leetcode Solution]Insertion Sort List
- [leetcode 147]Insertion Sort List
- LeetCode 147 Insertion Sort List
- LeetCode 147 Insertion Sort List(链表)
- [Leetcode] Insertion Sort List
- LeetCode-Insertion Sort List (Python)
- [LeetCode] Insertion Sort List 单向链表插入排序
- LeetCode(2):insertion-sort-list
- [LeetCode 147] Insertion Sort List