|
| 1 | +/* eslint-disable class-methods-use-this */ |
| 2 | +class Node { |
| 3 | + constructor(data, previous, next) { |
| 4 | + this.data = data; |
| 5 | + this.previous = previous; |
| 6 | + this.next = next; |
| 7 | + } |
| 8 | +} |
| 9 | + |
| 10 | +class DoublyLinkedList { |
| 11 | + constructor() { |
| 12 | + // head -> tail |
| 13 | + // head <- tail |
| 14 | + this.head = new Node(null, null, null); |
| 15 | + this.tail = new Node(null, null, null); |
| 16 | + this.head.next = this.tail; // head next point to tail |
| 17 | + this.tail.previous = this.head; // tail previous point to head |
| 18 | + this.size = 0; |
| 19 | + } |
| 20 | + |
| 21 | + addAtBeginning(value) { |
| 22 | + const newNode = new Node(value, this.head, this.head.next); |
| 23 | + this.head.next.previous = newNode; |
| 24 | + this.head.next = newNode; |
| 25 | + this.size += 1; |
| 26 | + } |
| 27 | + |
| 28 | + addAtEnd(value) { |
| 29 | + const newNode = new Node(value, this.tail.previous, this.tail); |
| 30 | + this.tail.previous.next = newNode; |
| 31 | + this.tail.previous = newNode; |
| 32 | + this.size += 1; |
| 33 | + } |
| 34 | + |
| 35 | + removeAtBeginning() { |
| 36 | + this.remove(this.head.next); |
| 37 | + this.size -= 1; |
| 38 | + } |
| 39 | + |
| 40 | + removeAtEnd() { |
| 41 | + this.remove(this.tail.previous); |
| 42 | + this.size -= 1; |
| 43 | + } |
| 44 | + |
| 45 | + remove(node) { |
| 46 | + const previousNode = node.previous; |
| 47 | + const nextNode = node.next; |
| 48 | + previousNode.next = nextNode; |
| 49 | + nextNode.previous = previousNode; |
| 50 | + } |
| 51 | + |
| 52 | + length() { |
| 53 | + return this.size; |
| 54 | + } |
| 55 | + |
| 56 | + display() { |
| 57 | + let address = this.head.next; |
| 58 | + while (address !== this.tail) { |
| 59 | + console.log(address.data); |
| 60 | + address = address.next; |
| 61 | + } |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +module.exports = DoublyLinkedList; |
0 commit comments