7/19/2020

[LeetCode] 147. Insertion Sort List

Problem : https://leetcode.com/problems/insertion-sort-list/

Time Complexity = O ( N ** 2 ),  N = length of input list.

/**
 * 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) {
        ListNode dummy = new ListNode();
        
        ListNode p = head;
        ListNode pre;
        ListNode cur;
        
        while (p != null) {
            pre = dummy;
            cur = dummy.next;
            
            while (cur != null && cur.val <= p.val) {
                pre = cur;
                cur = cur.next;
            }
            
            ListNode tmp = p.next;
            
            pre.next = p;
            p.next = cur;
            p = tmp;
        }
        
        return dummy.next;
    }
}

Edited on 12/14/2021. Replace with Java implementation.

No comments:

Post a Comment