A stack is a linear data structure that follows the LIFO (Last In, First Out) principle. It can be implemented using different data structures, including arrays and linked lists. When a stack is implemented using a linked list, elements are stored in individual nodes connected through links. This approach allows the stack to grow and shrink dynamically without requiring a fixed capacity. In this article, you will learn how to implement a stack using a linked list, understand its basic operations, and explore its advantages, limitations, and JavaScript examples.
Table of Contents
What Is a Stack Using a Linked List?
A stack using a linked list is a stack implementation in which elements are stored in nodes connected through links.
Each node contains two parts:
- Data: Stores the value of the element.
- Next: Stores a reference to the next node in the linked list.
A variable called top keeps track of the first node, which represents the top element of the stack.
The stack follows the LIFO principle, meaning the last element inserted is the first element removed.
Unlike a fixed-size array implementation, a linked-list-based stack can grow or shrink dynamically as elements are inserted or removed, depending on the available memory.
What Is a Linked List?
A linked list is a linear data structure in which elements are stored in separate nodes. Each node contains data and a reference to another node.
Unlike arrays, linked-list elements do not need to be stored in consecutive memory locations.
A singly linked list contains the following parts:
- Head: Stores a reference to the first node.
- Node: Stores the actual data.
- Next: Connects one node to the next node.
- Null: Indicates the end of the linked list.
In a stack implementation, the top variable points to the first node of the linked list.
How Does a Stack Using a Linked List Work?
A stack using a linked list works by inserting and removing nodes from the beginning of the linked list.
The top variable always points to the first node.
The following steps explain how it works:
- Initially, the top variable is set to null because the stack is empty.
- When an element is inserted, a new node is created.
- The new node is connected to the previous top node.
- The top variable is updated to point to the new node.
- When an element is removed, the current top node is deleted.
- The top variable is updated to point to the next node.
This approach allows insertion and deletion at the top without shifting other elements.
Basic Operations of Stack Using Linked List
A stack implemented using a linked list supports several basic operations.
1. Push Operation: The push operation inserts a new element at the top of the stack.A new node is created; its next reference points to the current top node, and the top variable is updated to the new node.
2. Pop Operation: The pop operation removes the top element from the stack. The top variable is updated to point to the next node. If the stack is empty, the operation results in stack underflow.
3. Peek Operation: The peek operation returns the value of the top element without removing it.
4. isEmpty Operation: The isEmpty operation checks whether the stack contains any elements.
If top is equal to null, the stack is empty.
5. Display Operation: The display operation visits each node starting from the top and prints its data until the end of the linked list is reached.
Stack Using Linked List Implementation in JavaScript
The following JavaScript program demonstrates how to implement a stack using a singly linked list.
// Implement a stack using a linked list and perform basic stack operations.
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class Stack {
constructor() {
this.top = null;
}
push(data) {
const newNode = new Node(data);
newNode.next = this.top;
this.top = newNode;
console.log(data + " inserted");
}
pop() {
if (this.isEmpty()) {
console.log("Stack Underflow");
return;
}
const removed = this.top.data;
this.top = this.top.next;
console.log(removed + " removed");
}
peek() {
if (this.isEmpty()) {
console.log("Stack is Empty");
return;
}
console.log("Top element: " + this.top.data);
}
isEmpty() {
return this.top === null;
}
display() {
if (this.isEmpty()) {
console.log("Stack is Empty");
return;
}
let current = this.top;
console.log("Stack elements:");
while (current !== null) {
console.log(current.data);
current = current.next;
}
}
}
const stack = new Stack();
stack.push(10);
stack.push(20);
stack.push(30);
stack.display();
stack.peek();
stack.pop();
stack.display();
console.log("Is Empty:", stack.isEmpty());
Output:
10 inserted
20 inserted
30 inserted
Stack elements:
30
20
10
Top element: 30
30 removed
Stack elements:
20
10
Is Empty: false
Explanation:
In this example, a stack is created using a linked list.
- The Node class creates individual nodes containing data and a next reference.
- The Stack class initializes the top variable to null.
- The push operation inserts 10, 20, and 30 at the beginning of the linked list.
- The display operation prints the elements from top to bottom.
- The peek operation returns 30 without removing it.
- The pop operation removes 30 and updates the top reference.
- The isEmpty operation checks whether the stack contains any nodes.
This implementation demonstrates how linked lists can be used to perform stack operations dynamically.
Example of Stack Using Linked List
The following example demonstrates how push and pop operations work using a linked list.
// Demonstrate push and pop operations using a linked-list-based stack.
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
let top = null;
function push(data) {
const newNode = new Node(data);
newNode.next = top;
top = newNode;
console.log(data + " inserted");
}
function pop() {
if (top === null) {
console.log("Stack Underflow");
return;
}
console.log(top.data + " removed");
top = top.next;
}
push(5);
push(15);
push(25);
pop();
pop();
pop();
pop();
Output:
5 inserted
15 inserted
25 inserted
25 removed
15 removed
5 removed
Stack Underflow
Explanation:
In this example, three elements are inserted into the stack using the push operation.
- The first push operation inserts 5.
- The second push operation inserts 15.
- The third push operation inserts 25.
- The first pop operation removes 25.
- The second pop operation removes 15.
- The third pop operation removes 5.
- The fourth pop operation attempts to remove an element from an empty stack, so stack underflow occurs.
This example demonstrates the LIFO principle using a linked-list-based stack.
Time Complexity of Stack Operations
The time complexity of stack operations using a linked list is generally efficient because insertion and deletion take place at the beginning of the list.
| Operation | Time Complexity | Description |
|---|---|---|
| Push | O(1) | Inserts a new node at the top. |
| Pop | O(1) | Removes the top node. |
| Peek | O(1) | Accesses the top element. |
| isEmpty | O(1) | Checks whether the stack is empty. |
| Display | O(n) | Visits all nodes in the stack. |
Here, n represents the number of nodes in the stack.
Advantages of Stack Using Linked List
Implementing a stack using a linked list provides several benefits.
- Dynamic Size: The stack can grow or shrink as elements are inserted or removed.
- No Fixed Capacity: Unlike a fixed-size array implementation, it does not require a predefined maximum size.
- Efficient Operations: Push and pop operations generally take O(1) time.
- No Element Shifting: Insertion and deletion at the beginning do not require shifting other elements.
- Flexible Memory Usage: Memory is allocated when new nodes are created and becomes available for garbage collection when nodes are no longer referenced.
Limitations of Stack Using Linked List
Although a linked-list-based stack is useful, it also has some limitations.
- Extra Memory: Each node requires additional memory to store a reference to the next node.
- Memory Allocation: Creating and deleting nodes involves memory allocation and garbage collection overhead.
- No Direct Index Access: Elements cannot be accessed directly using indexes like array elements.
- Pointer Management: The next references and top variable must be updated correctly.
- Memory Limitations: The stack can still run out of available memory even though it does not have a fixed capacity.
Difference Between Stack Using Array and Linked List
A stack can be implemented using either an array or a linked list. Both implementations follow the LIFO principle, but they differ in memory management and implementation.
| Stack Using Array | Stack Using Linked List |
|---|---|
| Elements are stored in an array. | Elements are stored in linked nodes. |
| A fixed-size implementation has a predefined capacity. | The stack can grow dynamically. |
| No extra pointer is required for each element. | Each node stores a reference to the next node. |
| Push and pop operations generally take O(1) time. | Push and pop operations generally take O(1) time. |
| Resizing may be required when capacity is reached. | New nodes are created when elements are inserted. |
| Can provide better memory locality. | Nodes may be stored in different memory locations. |
Common Mistakes to Avoid
- Incorrect Top Initialization: Always initialize the top variable to null when the stack is empty.
- Incorrect Node Connection: Make sure the new node points to the previous top node before updating the top variable.
- Ignoring Stack Underflow: Check whether the stack is empty before performing the pop operation.
- Updating Top Incorrectly: When removing an element, update top to the next node.
- Confusing Arrays with Linked Lists: Remember that linked-list-based stacks use nodes and references instead of array indexes.
Frequently Asked Questions
1. What is a stack using a linked list?
A stack using a linked list is a stack implementation in which elements are stored in connected nodes and accessed according to the LIFO principle.
2. Why is a linked list used to implement a stack?
A linked list is used because it allows a stack to grow and shrink dynamically without requiring a fixed maximum capacity.
3. What is the role of the top variable?
The top variable stores a reference to the first node of the linked list, which represents the top element of the stack.
4. What is the time complexity of push and pop operations using a linked list?
Both push and pop operations generally take O(1) time because they insert or remove nodes directly at the beginning of the linked list.
5. Which is better: a stack using an array or a linked list?
Both have advantages. Arrays can provide better memory locality and less per-element overhead, while linked lists support dynamic growth without resizing a fixed-size array. The better choice depends on the application's requirements.
0 Comments