Creating the StackLinkedList class
We can also use the LinkedList
class and its variations as internal data structures to create other data structures such as stack, queue, and deque. In this topic, we will learn how to create the stack data structure (covered in Chapter 4, Stacks).
The StackLinkedList
class structure and the methods push
and pop
are declared as follows:
class StackLinkedList { constructor() { this.items = new DoublyLinkedList(); // {1} } push(element) { this.items.push(element); // {2} } pop() { if (this.isEmpty()) { return undefined; } return this.items.removeAt(this.size() - 1); // {3} } }
For the StackLinkedList
class, instead of using an array or a JavaScript object to store the items
, we will use a DoublyLinkedList
({1}
). The reason for using the doubly linked list instead of the linked list is that for the stack, we will be inserting elements at the end of the list ({2}
) and also removing elements from the end of the list ({3}
)....