LeetCode 147. Insertion Sort List (对链表进行插入排序)

题目标签:Sort

  遍历Linked List,把每一个点, 放到新的list里 合适的位置。具体看code。

 

Java Solution: 

Runtime:  30 ms, faster than 41.35% 

Memory Usage: 39MB, less than 72.23%

完成日期:6/13/2020

关键点:Linked List, Insertion Sort

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode insertionSortList(ListNode head) {
        if(head == null) {
            return head;
        }
        
        ListNode helper = new ListNode(0); // new starter of the sorted list
        ListNode cur = head; // this node will be inserted
        ListNode pre = helper; // insert node between pre and pre.next
        ListNode next = null; // the next node will be inserted
        
        // go through list
        while(cur != null) {
            next = cur.next;
            
            // find the right place to insert next node
            while(pre.next != null && pre.next.val < cur.val) {
                pre = pre.next;
            }
            
            // insert between pre and pre.next
            cur.next = pre.next;
            pre.next = cur;
            pre = helper;
            cur = next;
        }
        
        return helper.next;
    }
}

参考资料:https://leetcode.com/problems/insertion-sort-list/discuss/46420/An-easy-and-clear-way-to-sort-(-O(1)-space-)

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

posted @ 2020-06-14 00:33  Jimmy_Cheng  阅读(89)  评论(0编辑  收藏  举报