GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • LeetCodeJavascript.com
  • Star on GitHub

This view

  • Original page
  • New address

GeezerVison is showing leetcodejavascript.com — #148 - Sort List - LeetCode JavaScript Solutions

Back to all solutions

#148 - Sort List

Medium • View on LeetCode • View on GitHub
Sorting Two Pointers Linked List Divide and Conquer Merge Sort

Problem Description

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

Solution

/**
 * 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) {
  if (!head || !head.next) return head;
  let fast = head;
  let slow = head;
  while (fast.next && fast.next.next) {
    fast = fast.next.next;
    slow = slow.next;
  }
  const middle = slow.next;
  slow.next = null;
  return mergeList(sortList(head), sortList(middle));
};

function mergeList(a, b) {
  const ordered = new ListNode(-1);
  let list = ordered;

  while (a && b) {
    list.next = a.val < b.val ? a : b;
    list = list.next;
    if (a.val < b.val) {
      a = a.next;
    } else {
      b = b.next;
    }
  }

  list.next = a ?? b;
  return ordered.next;
}
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.