Introduction
A stack is a data structure that follows the Last In, First Out (LIFO) principle. In simple terms, this means the last item added to the stack is the first one to be removed. Imagine a stack of plates: the last plate placed on top is the first one you take off.
In this guide, we'll build a stack using a linked list in JavaScript. If you're new to JavaScript and data structures, don't worry! We'll break down each step in a beginner-friendly way.
Key Stack Operations
- Push - Add an item to the top of the stack.
- Pop - Remove and return the item at the top of the stack.
- Peek - Return the top item without removing it.
- isEmpty - Check if the stack has any items.
- size - Return the number of items in the stack.
- clear - Remove all items from the stack.
Stack Implementation Using a Linked List
Since linked lists are built with nodes, we’ll start by creating a Node structure. Each node has two parts: the value it stores and a next pointer that points to the next node.
Explanation of the Code
-
Creating the Node:
- Each
Node represents an item in the stack and has a value and a next pointer.
this.value stores the node’s data, and this.next points to the next node in the stack.
-
Stack Operations:
- Push: Creates a new node, links it to the current
top of the stack, then updates top to the new node.
- Pop: Removes the node at the
top of the stack, moves top to the next node, and returns the value of the removed node.
- Peek: Returns the
value of the top node without removing it.
- isEmpty: Checks if
size is 0, indicating the stack is empty.
- Size: Returns the
size of the stack.
- Clear: Resets
top to null and size to 0, effectively emptying the stack.
Example Usage
Explanation of Each Operation
- Push(10), Push(20), Push(30): Adds 10, then 20, and finally 30 to the stack. Stack state:
30 -> 20 -> 10.
- Pop(): Removes and returns 30, the current top of the stack. Stack state:
20 -> 10.
- Peek(): Returns 20, the current top of the stack without removing it.
- isEmpty(): Checks if the stack is empty. Returns
false because the stack has items.
- getSize(): Returns the stack size, which is
2 after the pop.
- Clear(): Empties the stack, resetting it.
isEmpty() now returns true.
Conclusion
Using a linked list to implement a stack provides flexibility and efficiency, especially for dynamic operations. Each operation on the stack is optimized for adding and removing items from the top, following the LIFO (Last In, First Out) principle. With these operations, you now have a complete stack implementation ready for various problem-solving scenarios.