Leetcode: Insertion Sort List
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)。
第二遍做法:
1 public class Solution { 2 public ListNode insertionSortList(ListNode head) { 3 ListNode dummy = new ListNode(-1); 4 ListNode cursor = dummy; 5 while (head != null) { 6 ListNode next = head.next; 7 while (cursor.next!=null && cursor.next.val<=head.val) { 8 cursor = cursor.next; 9 } 10 head.next = cursor.next; 11 cursor.next = head; 12 head = next; 13 cursor = dummy; 14 } 15 return dummy.next; 16 } 17 }
第一遍做法:
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 }
上面程序注释如下:
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; //after one search, put pre back to its original place 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 }