Journal Archive

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var sortList = function(head) {
	// base case
    if (!head || !head.next) return head;
    
	// halving the list
    let slowP = head;
    let fastP = head;
    let prevP = null;
    
    while (fastP && fastP.next) {
        prevP = slowP
        slowP = slowP.next
        fastP = fastP.next.next
    }
    
    // splitting the list in two
    prevP.next = null
    
    let left = sortList(head);
    let right = sortList(slowP);
    
    // merging sort
    
    const newHead = new ListNode(0);
    let temp = newHead;
    
    while (left && right) {
        if (left.val < right.val) {
            temp.next = left;
            left = left.next
        } else {
            temp.next = right;
            right = right.next
        }
        temp = temp.next;
    }
    
    if (left) {
        temp.next = left;
    }
    
    if (right) {
        temp.next = right;
    }
    
    return newHead.next;
    
    
};

Day 74: Solving one of LeetCode problems

148. Sort List Difficulty - Medium

Given the head of a linked list, return the list after sorting it in ascending order.

 

Example 1:

Input: head = [4,2,1,3]
Output: [1,2,3,4]
		

Example 2:

Input: head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]
		

Example 3:

Input: head = []
Output: []