首页 > 代码库 > Leetcode: Insertion Sort List
Leetcode: Insertion Sort List
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个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。