9. Doubly Linked List - marinakosova/master-the-coding-interview GitHub Wiki
Doubly Linked List
Common operations on a doubly linked list may include:
adding nodes to both ends of the list
removing nodes from both ends of the list
finding, and removing, a node from anywhere in the list
traversing (or traveling through) the list
Doubly Linked List implementation (from Codecademy):
classNode{constructor(data){this.data=data;this.next=null;this.previous=null;}setNextNode(node){if(nodeinstanceofNode||node===null){this.next=node;}else{thrownewError('Next node must be a member of the Node class')}}setPreviousNode(node){if(nodeinstanceofNode||node===null){this.previous=node;}else{thrownewError('Previous node must be a member of the Node class')}}getNextNode(){returnthis.next;}getPreviousNode(){returnthis.previous;}}classDoublyLinkedList{constructor(){this.head=null;this.tail=null;}addToHead(data){constnewHead=newNode(data);constcurrentHead=this.head;if(currentHead){currentHead.setPreviousNode(newHead);newHead.setNextNode(currentHead);}this.head=newHead;if(!this.tail){this.tail=newHead;}}addToTail(data){constnewTail=newNode(data);constcurrentTail=this.tail;if(currentTail){currentTail.setNextNode(newTail);newTail.setPreviousNode(currentTail);}this.tail=newTail;if(!this.head){this.head=newTail;}}removeHead(){constremovedHead=this.head;if(!removedHead){return;}this.head=removedHead.getNextNode();if(this.head){this.head.setPreviousNode(null);}if(removedHead===this.tail){this.removeTail();}returnremovedHead.data;}removeTail(){constremovedTail=this.tail;if(!removedTail){return;}this.tail=removedTail.getPreviousNode();if(this.tail){this.tail.setNextNode(null);}if(removedTail===this.head){this.removeHead();}returnremovedTail.data;}removeByData(data){letnodeToRemove;letcurrentNode=this.head;while(currentNode!==null){if(currentNode.data===data){nodeToRemove=currentNode;break;}currentNode=currentNode.getNextNode();}if(!nodeToRemove){returnnull;}if(nodeToRemove===this.head){this.removeHead();}elseif(nodeToRemove===this.tail){this.removeTail();}else{constnextNode=nodeToRemove.getNextNode();constpreviousNode=nodeToRemove.getPreviousNode();nextNode.setPreviousNode(previousNode);previousNode.setNextNode(nextNode);}returnnodeToRemove;}printList(){letcurrentNode=this.head;letoutput='<head> ';while(currentNode!==null){output+=currentNode.data+' ';currentNode=currentNode.getNextNode();}output+='<tail>';console.log(output);}}constsubway=newDoublyLinkedList();subway.addToHead('TimesSquare');subway.addToHead('GrandCentral');subway.addToHead('CentralPark');subway.printList();subway.addToTail('PennStation');subway.addToTail('WallStreet');subway.addToTail('BrooklynBridge');subway.printList();subway.removeTail();subway.removeHead();subway.printList();subway.removeByData('TimesSquare');subway.printList();