Open In App

How to traverse Doubly Linked List in JavaScript?

Last Updated : 11 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

This article will demonstrate the Doubly Linked List Traversal using JavaScript. Traversal refers to the steps or movement of the pointer to access any element of the list.

Types of Traversal in Doubly Linked List Using JavaScript

  • Normal Traversal: Traversing the list from Head to Tail of the list.
  • Reverse Traversal: Traversing the list from the Tail element to the Head element of the list i.e. in reverse order.

Normal traversal

This is head to tail movement of the pointer in a list. The normal traversal is done as:

  • Create a pointer named curr as the current pointer.
  • Assign the value of the head to the curr pointer.
  • Move the curr pointer till the end and display output.
    • curr => curr.next

Example:

Javascript




// To traverse and display the list
display() {
    // Check if the List is empty
    if (!this.isEmpty()) {
        // traverse the list using new current pointer
        let curr = this.head;
        console.log("Required list is");
 
        while (curr !== null) {
            // Display element
            console.log(curr.data);
 
            // Shift the current pointer
            curr = curr.next;
        }
    }
}


Reverse traversal

This is head to tail movement of the pointer in a list. The normal traversal is done as:

  • Create a pointer named curr as the current pointer.
  • Assign the value of the tail to the curr pointer.
  • Move the curr pointer backward till start and display output.
    • curr => curr.prev

Example:

Javascript




// To display/ traverse list in reverse
displayRev() {
    // Check if the List is empty
    if (!this.isEmpty()) {
        // traverse the list using new current pointer
        let curr = this.tail;
        console.log('Required list in reverse order is')
 
        while (curr !== null) {
            // Display element
            console.log(curr.data);
 
            // Shift the current pointer
            curr = curr.prev;
        }
    }
}


Implementation of traversal in Doubly Linked List

Example: In this example, we will add some items in the linked list and Display the final list in both normal and reverse order by traversing in both direction.

Javascript




// Doubly Linked list Node
class Node {
    // Constructor to create a new node
    // next and prev is by default initialized as null
    constructor(val) {
        // To store the value
        this.data = val;
 
        // To link the next Node
        this.next = null;
 
        // TO link the previous Node
        this.prev = null;
    }
}
 
// Doubly Linked List
class DoublyLinkedList {
    // Constructor to create a new linked list
    constructor() {
        // To contain the first item of the list
        this.head = null;
 
        // To contain the last item of the list
        this.tail = null;
    }
 
    // To check if the list is empty
    isEmpty() {
        if (this.head == null) return true;
        return false;
    }
 
    // Method to add item at the last of doubly linked list
    insertEnd(val) {
        // Create a temporary variable
        let temp = new Node(val);
 
        // If the list is empty link assign
        // new node to both head and tail
        if (this.head == null) {
            this.head = temp;
            this.tail = temp;
        }
 
        // else add item to the tail and shift tail
        else {
            temp.prev = this.tail;
            this.tail.next = temp;
            this.tail = this.tail.next;
        }
        console.log('inserted at end',val)
 
    }
 
    insertStart(val) {
        // Create a temporary variable
        let temp = new Node(val);
 
        // If the list is empty link assign
        // new node to both head and tail
        if (this.head == null) {
            this.head = temp;
            this.tail = temp;
        }
 
        // else add item to the head and shift head backward
        else {
            temp.next = this.head;
            this.head.prev = temp;
            this.head = temp;
        }
        console.log('inserted at start',val)
    }
 
    // method to insert value at given index
    insertAt(val, pos) {
        // If the index is 0 use insertStart
        // method to insert value as 0 position
        if (pos == 0) return this.insertStart(val);
        let index = pos;
        let curr = this.head;
        // Iterate to the element present
        // just before given index
        while (pos > 1) {
            pos -= 1;
            // If list do not contain enough elements
            if (curr === null)
                return console.log(
                    "Incorrect Position! Index does not exist.",
                    pos,
                    curr.data
                );
 
            // Shift the poiter at every iteration
            curr = curr.next;
        }
 
        // After reaching required index create new node
        let temp = new Node(val);
 
        // Insert node at the required position
        temp.next = curr.next;
        temp.prev = curr;
        curr.next.prev = temp;
        curr.next = temp;
        console.log('inserted at index',index,'value',val)
 
    }
 
    // To traverse and display the list
    display() {
        // Check if the List is empty
        if (!this.isEmpty()) {
            // traverse the list using new current pointer
            let curr = this.head;
            console.log('Required list is')
 
            while (curr !== null) {
                // Display element
                console.log(curr.data);
 
                // Shift the current pointer
                curr = curr.next;
            }
        }
    }
    displayRev() {
        // Check if the List is empty
        if (!this.isEmpty()) {
            // traverse the list using new current pointer
            let curr = this.tail;
            console.log('Required list in reverse order is')
 
            while (curr !== null) {
                // Display element
                console.log(curr.data);
 
                // Shift the current pointer
                curr = curr.prev;
            }
        }
    }
}
 
// Create new Doubly Linked List
const dll = new DoublyLinkedList();
 
// Add elements in the list
dll.insertEnd(25);
dll.insertEnd(27);
dll.insertStart(17);
dll.insertStart(29);
 
dll.insertAt(65,3);
 
// Display the list
dll.display();
// Display the reverse list
dll.displayRev();


Output

inserted at end 25
inserted at end 27
inserted at start 17
inserted at start 29
inserted at index 3 value 65
Required list is
29
17
25
65
27
Required list in reverse order is
27
65
25
17
29






Previous Article
Next Article

Similar Reads

Javascript Program for Rotate Doubly linked list by N nodes
Given a doubly linked list, rotate the linked list counter-clockwise by N nodes. Here N is a given positive integer and is smaller than the count of nodes in linked list. N = 2Rotated List: Examples: Input : a b c d e N = 2 Output : c d e a b Input : a b c d e f g h N = 4 Output : e f g h a b c d Asked in Amazon To rotate the Doubly linked list, we
4 min read
Implementation of Doubly Linked List in JavaScript
This article will demonstrate the Implementation of Doubly Linked List In JavaScript. A doubly linked list (DLL) is a special type of linked list in which each node contains a pointer to the previous node as well as the next node of the linked list. Doubly Linked List in JavaScriptTo create we have to create the following classes: Node Class: To im
4 min read
Insert Operation in Doubly Linked List using JavaScript
This article demonstrates the insert operation in a Doubly Linked List using JavaScript. The insertion in the Doubly linked list follows the given Steps. Steps to Insert Element in Doubly Linked ListCreate a new Node element with the input data/ value.Link the new node previous to the current element and next to the current's next node.temp.prev =
6 min read
Delete Operations in Doubly Linked List using JavaScript
This article will demonstrate how to perform delete operations in a Doubly Linked List Data Structure using JavaScript. We will see different approaches to deleting elements from the Doubly Linked List. Steps to Delete Element Node from Doubly Linked ListA doubly linked list has two pointers that link it with the previous and next node. So if we ha
11 min read
Javascript Program For Merge Sort For Doubly Linked List
Given a doubly linked list, write a function to sort the doubly linked list in increasing order using merge sort.For example, the following doubly linked list should be changed to 24810 Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Merge sort for singly linked list is already discussed. The important change her
3 min read
Javascript Program For Deleting A Node In A Doubly Linked List
Pre-requisite: Doubly Link List Set 1| Introduction and Insertion Write a function to delete a given node in a doubly-linked list. Original Doubly Linked List  Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Approach: The deletion of a node in a doubly-linked list can be divided into three main categories:  After
4 min read
Javascript Program For Reversing A Doubly Linked List
Given a Doubly Linked List, the task is to reverse the given Doubly Linked List. See below diagrams for example. (a) Original Doubly Linked List (b) Reversed Doubly Linked List Here is a simple method for reversing a Doubly Linked List. All we need to do is swap prev and next pointers for all nodes, change prev of the head (or start) and change the
5 min read
Javascript Program For QuickSort On Doubly Linked List
Following is a typical recursive implementation of QuickSort for arrays. The implementation uses last element as pivot. C/C++ Code <script> /* A typical recursive implementation of Quicksort for array*/ /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (small
5 min read
JavaScript Program to Delete Middle of Doubly Linked List
We are given a doubly linked list and we have to write a JavaScript program to delete the middle node of the list and print the newly formed linked list after the deletion. Example: Input: 1 <-> 2 <-> 3 <-> 4 <-> 5Output: 1 <-> 2 <-> 4 <-> 5Below are the different approaches to delete the middle of a doubly
4 min read
JavaScript Program to Count Nodes in Doubly Linked List
A Doubly Linked List is a type of linked list where each node contains a reference to the previous and next nodes in the sequence. Counting nodes in a Doubly Linked List involves iterating through the list and incrementing a counter for each node encountered. Below are the approaches to count nodes in doubly linked list: Table of Content Recursive
3 min read