nodeblogger.com

Reverse a Linked List in Javascript

Data Structure, Featured, Javascript, Linked List

So in last post we have create a linked list and develop function to insert and remove node in javascript. Today we are going to reverse the linked list in javascript.

So as a first step we will create a linked list. Please refer to my previous blog to check how to create a linked list.

Create Linked List and Remove node in Javascript

Now we will reverse the nodes one by one as shown in below code.

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();

    }

In the next post we are going to see how can we find the middle element of linked list efficiently.

Leave a Reply