Skip to content

Commit

Permalink
Sort List (Medium)
Browse files Browse the repository at this point in the history
  • Loading branch information
wogha95 committed Jul 9, 2024
1 parent 21718da commit 5f3ea0d
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions Divide & Conquer/Sort List (Medium)/max.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// 1차 (PASS)
// 시간복잡도: O(N * logN)
// 공간복잡도: O(logN)
// @see https://www.geeksforgeeks.org/merge-sort-for-linked-list/

/**
* 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) {
return divideAndConquer(head);

function divideAndConquer(h) {
if (h === null || h.next === null) {
return h;
}

const center = getCenterHead(h);
const centerNext = center.next;
center.next = null;

const left = divideAndConquer(h);
const right = divideAndConquer(centerNext);

return sortedMerge(left, right);
}

function getCenterHead(h) {
if (h === null) {
return h;
}

let fast = h;
let slow = h;

while (fast.next !== null && fast.next.next !== null) {
slow = slow.next;
fast = fast.next.next;
}

return slow;
}

function sortedMerge(a, b) {
let result = null;

if (a === null) {
return b;
}
if (b === null) {
return a;
}

if (a.val < b.val) {
result = a;
result.next = sortedMerge(a.next, b);
} else {
result = b;
result.next = sortedMerge(a, b.next);
}

return result;
}
};

0 comments on commit 5f3ea0d

Please sign in to comment.