w3resource

JavaScript Exercises: Print a Doubly Linked lists in reverse order

JavaScript Data Structures: Exercise-9 with Solution

Write a JavaScript program to create a Doubly Linked lists of n nodes and display it in reverse order.

Sample Solution:

JavaScript Code:

class Node {
	constructor(value) {
		this.value = value;
		this.next = null;
		this.previous = null;
	}
}

class DoublyLinkedList {
	constructor(value) {
		this.head = {
			value: value,
			next: null,
			previous: null
		};
		this.length = 0;
		this.tail = this.head;
	}

  add(newNode) {
    if (this.head === null) {
    this.head = newNode;
    this.tail = newNode;
    } 
    else
    {
    newNode.previous = this.tail;
    this.tail.next = newNode;
    this.tail = newNode;
  }

  this.length++;
   }
  
 reverse() {
    let current = this.head;
    let temp = null;
    while (current != null) {
        temp = current.previous;
        current.previous = current.next;
        current.next = temp;
        current = current.previous;
    }
    if (temp != null) {
        this.head = temp.previous;
    }
    return this.head;
}

  
 printList() {
		let current = this.head;
		let result = [];
		while (current !== null) {
			result.push(current.value);
			current = current.next;
		}
		console.log(result.join(' '));
		return this;
	}
}

let numList = new DoublyLinkedList();
numList.add(new Node(2));
numList.add(new Node(3));
numList.add(new Node(4));
numList.add(new Node(5));
numList.add(new Node(6));
numList.add(new Node(7));
console.log("Original Doubly Linked Lists:")
numList.printList();
console.log("Reverse Linked list:")
numList.reverse();
numList.printList();

Sample Output:

Original Doubly Linked Lists:
 2 3 4 5 6 7
Reverse Linked list:
7 6 5 4 3 2 

Flowchart:

Flowchart: JavaScript Exercises: Print a Doubly Linked lists in reverse order.
Flowchart: JavaScript Exercises: Print a Doubly Linked lists in reverse order.

Live Demo:

See the Pen javascript-doubly-linked-list-exercise-9 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Linked List Previous: Get the value of a node at a given position in a Doubly Linked List.
Linked List Next: Convert a Doubly Linked lists into an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

JavaScript: Tips of the Day

Creates an array of elements, ungrouping the elements in an array produced by zip and applying the provided function

Example:

const tips_unzip = (arr, fn) =>
  arr
    .reduce(
      (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc),
      Array.from({
        length: Math.max(...arr.map(x => x.length))
      }).map(x => [])
    )
    .map(val => fn(...val));

console.log(tips_unzip([[2, 15, 200], [3, 25, 300]], (...args) => args.reduce((acc, v) => acc + v, 0)));

Output:

[5, 40, 500]