Last active
May 2, 2022 10:26
-
-
Save harbirchahal/a867a45192cbafbf9c6888e1b3875531 to your computer and use it in GitHub Desktop.
Single LL Operations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* function ListNode(val, next) { | |
* this.val = (val===undefined ? 0 : val) | |
* this.next = (next===undefined ? null : next) | |
* } | |
*/ | |
function length(head) { | |
if (head) { | |
let count = 1; | |
let tail = head; | |
while (tail.next) { | |
tail = tail.next; | |
count += 1; | |
} | |
return [tail, count]; | |
} | |
return [head, 0]; | |
} | |
function middle(head) { | |
let slow = head; | |
let fast = head; | |
while (fast && fast.next) { | |
slow = slow.next; | |
fast = fast.next.next; | |
} | |
return slow; | |
} | |
function reverse(head) { | |
let prev = null; | |
let curr = head; | |
let next = head.next; | |
while (curr) { | |
curr.next = prev; | |
prev = curr; | |
curr = next; | |
next = next && next.next; | |
} | |
return prev; | |
} | |
function merge(list1, list2) { | |
const head = new ListNode(); | |
let node = head; | |
while (list1 && list2) { | |
if (list1.val < list2.val) { | |
node.next = list1; | |
list1 = list1.next; | |
} else { | |
node.next = list2; | |
list2 = list2.next; | |
} | |
node = node.next; | |
} | |
node.next = list1 || list2; | |
return head.next; | |
} | |
function rotateRight(head, k) { | |
if (head && head.next) { | |
const [tail, len] = length(head); | |
const rotations = k % len; | |
const skip = len - rotations; | |
tail.next = head; | |
let node = head; | |
for (let i = 0; i < skip - 1; i++) { | |
node = node.next; | |
} | |
head = node.next; | |
node.next = null; | |
} | |
return head; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment