Created
May 27, 2021 03:33
-
-
Save CarlaTeo/fdfd4ced1ac1556add6130a7c45f9391 to your computer and use it in GitHub Desktop.
[JS] Reverse linked list
This file contains 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 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