Reverse Linked List in Javascript

Reverse a Linked List in Javascript

Data Structure, Linked List, Trending

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.

  1. We will initalize two pointers first as current HEAD, second as NEXT element
  2. Iterate through Linked List, In Loop we will do the following.
  3. Store second.next in temp variable.
  4. Store first element in second.next
  5. Assign Second element as first element.
  6. 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))

References:

https://www.geeksforgeeks.org/reverse-a-linked-list/

One thought on “Reverse a Linked List in Javascript

Leave a Reply