Skip to content

Instantly share code, notes, and snippets.

@CarlaTeo
Created May 27, 2021 03:33
Show Gist options
  • Save CarlaTeo/fdfd4ced1ac1556add6130a7c45f9391 to your computer and use it in GitHub Desktop.
Save CarlaTeo/fdfd4ced1ac1556add6130a7c45f9391 to your computer and use it in GitHub Desktop.
[JS] Reverse linked list
function reverseLinkedList(head) {
let prev = null;
let cur = head;
let next = null;
while(cur) {
next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
// ------------------------------------ Test ----------------------------- //
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
console.log(reverseLinkedList()); // null
let node1 = new Node(1);
console.log( reverseLinkedList(node1)); // 1
node1 = new Node(1);
let node2 = new Node(2);
node1.next = node2;
console.log(reverseLinkedList(node1)); // 2-1
node1 = new Node(1);
node2 = new Node(2);
node1.next = node2;
let node3 = new Node(3);
node2.next = node3;
console.log(reverseLinkedList(node1)); //3-2-1
node1 = new Node(1);
node2 = new Node(2);
node1.next = node2;
node3 = new Node(3);
node2.next = node3;
let node4 = new Node(4);
node3.next = node4;
console.log(reverseLinkedList(node1)); //4-3-2-1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment