Reverse a Linked List in Javascript
In this post we are going to reverse a linked list in javascript.
Input: Head of following linked list
1->2->3->4->NULL
Output: Linked list should be changed to,
4->3->2->1->NULL
To reverse a linked list we are going to use the iterative approach discussed below.
- We will initalize two pointers first as current HEAD, second as NEXT element
- Iterate through Linked List, In Loop we will do the following.
- Store second.next in temp variable.
- Store first element in second.next
- Assign Second element as first element.
- Assign temp as second element.
Below is the implementation of the above approach:
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor(head = null) {
this.head = head;
}
add(data) {
let node = new Node(data);
if (this.head == null)
this.head = node;
else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = node;
}
}
printList() {
let arr = [];
let current = this.head;
while (current != null) {
arr.push(current.data);
current = current.next;
}
return arr;
}
reverse(head = this.head) {
let first = this.head;
let second = first.next;
while (second) {
let temp = second.next;
second.next = first;
first = second;
second = temp
}
this.head.next = null;
this.head = first;
return this.printList();
}
}
let ll = new LinkedList();
ll.add(10);
ll.add(20);
ll.add(30);
ll.add(40);
ll.add(50);
console.log(ll.reverse())
console.log(JSON.stringify(ll))
One thought on “Reverse a Linked List in Javascript”