Skip to content

Instantly share code, notes, and snippets.

@parkerproject
Created April 25, 2023 23:26
Show Gist options
  • Save parkerproject/4b43c4a6de18a1c2c64616428fe23903 to your computer and use it in GitHub Desktop.
Save parkerproject/4b43c4a6de18a1c2c64616428fe23903 to your computer and use it in GitHub Desktop.
class ListNode {
constructor(value) {
this.value = value;
this.next = null;
}
}
function reverseLinkedList(head, prev = null) {
if (head === null) {
return prev;
}
const nextNode = head.next;
head.next = prev;
return reverseLinkedList(nextNode, head);
}
// Example usage:
const createLinkedListFromArray = (arr) => {
const dummyHead = new ListNode(null);
let current = dummyHead;
for (let value of arr) {
current.next = new ListNode(value);
current = current.next;
}
return dummyHead.next;
};
const printLinkedList = (head) => {
let current = head;
let result = [];
while (current) {
result.push(current.value);
current = current.next;
}
console.log(result.join(' -> '));
};
const array = [1, 2, 3, 4, 5];
const head = createLinkedListFromArray(array);
printLinkedList(head); // Output: 1 -> 2 -> 3 -> 4 -> 5
const reversedHead = reverseLinkedList(head);
printLinkedList(reversedHead); // Output: 5 -> 4 -> 3 -> 2 -> 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment