Reverse doubly linked list javascript

Reverse doubly linked list in node js

Js program for Reverse doubly linked list. Here more information.

// Node JS program for // Reverse the node in doubly linked list // Define class of linked list Node class LinkNode { constructor(data) { this.data = data; this.next = null; this.prev = null; } } class DoublyLinkedList { constructor() { this.head = null; this.tail = null; } // Insert new node at end position insert(value) { // Create a node var node = new LinkNode(value); if (this.head == null) { // Add first node this.head = node; this.tail = node; return; } // Add node at last position this.tail.next = node; node.prev = this.tail; this.tail = node; } // Display node element of doubly linked list display() { if (this.head == null) { console.log("Empty Linked List"); } else { process.stdout.write("\nLinked List Head to Tail :"); // Get first node of linked list var temp = this.head; // iterate linked list while (temp != null) { // Display node value process.stdout.write(" " + temp.data); // Visit to next node temp = temp.next; } process.stdout.write("\nLinked List Tail to Head :"); // Get last node of linked list temp = this.tail; // iterate linked list while (temp != null) { // Display node value process.stdout.write(" " + temp.data); // Visit to prev node temp = temp.prev; } } } // Reverse linked list nodes reverse() { if (this.head == null) { console.log("Empty Linked List"); } else { var temp = this.head; var back = null; // Make new tail this.tail = this.head; // Change node link while (temp != null) { // Make new upcoming node as to head this.head = temp; temp = temp.next; // Modified current node link this.head.prev = temp; this.head.next = back; back = this.head; } } } } function main() { var dll = new DoublyLinkedList(); // Insert following linked list nodes dll.insert(1); dll.insert(2); dll.insert(3); dll.insert(4); dll.insert(5); dll.insert(6); dll.insert(7); dll.insert(8); dll.display(); dll.reverse(); process.stdout.write("\nAfter reverse"); dll.display(); } // Start program execution main();

Output

Linked List Head to Tail : 1 2 3 4 5 6 7 8 Linked List Tail to Head : 8 7 6 5 4 3 2 1 After reverse Linked List Head to Tail : 8 7 6 5 4 3 2 1 Linked List Tail to Head : 1 2 3 4 5 6 7 8