In this tutorial, we are going to learn how to implement a stack data structure using a linked list in Java.
By the end of this tutorial, you will have a clear understanding of stack operations and how to use a linked list in Java to create a dynamic stack. This knowledge will help you to manage data more efficiently.
There are two ways to implement a stack data structure:
- Using Array
- Using Linked List
Let's see the Stack implementation using Linked List in Java.
Stack implementation using Linked List in Java
In a linked list-based stack implementation, the head of the list is the top of the stack. The push operation creates a new node with the new element, points its next reference to the current top node and makes it the new top. The pop operation returns the value of the current top node and moves the top to the next node.
public class StackUsingLinkedList {
private StackNode root;
static class StackNode {
int data; // Store node value
StackNode next; // Store address to the next node
StackNode(int data) {
this.data = data;
}
}
// Adding new item into the stack
public void push(int data) {
StackNode newNode = new StackNode(data);
// checks stack is empty
if (root == null) {
root = newNode;
} else {
StackNode temp = root;
root = newNode;
newNode.next = temp;
}
System.out.println(data + " pushed to the stack");
}
// Removing an item from the stack
public void pop() {
// checks stack is empty
if (root == null) {
System.out.println("Stack is Empty");
return;
}
int popped = root.data;
root = root.next;
System.out.println(popped + " popped from the stack");
}
// Returns top element of the stack.
public void peek() {
// check stack is empty
if (root == null) {
System.out.println("Stack is empty");
} else {
System.out.println("Top element of stack: " + root.data);
}
}
// Print linked list items without modifying the stack
public void printLinkedList() {
StackNode temp = root;
// Traverse the linked list until reaching the end
while (temp != null) {
System.out.print(temp.data + " ");
// Move to the next node
temp = temp.next;
}
}
// Driver code
public static void main(String[] args) {
StackUsingLinkedList stack = new StackUsingLinkedList();
stack.push(10); // Insert item
stack.push(20); // Insert item
stack.push(30); // Insert item
stack.pop(); // Remove item
stack.peek(); // Return top item of the stack
stack.push(50); // Insert item
stack.push(60); // Insert item
stack.pop(); // Remove item
stack.printLinkedList(); // Print linked list items
}
}
10 pushed to the stack 20 pushed to the stack 30 pushed to the stack 30 popped from the stack Top element of stack: 20 50 pushed to the stack 60 pushed to the stack 60 popped from the stack 50 20 10
Time complexity: O(1) for push, pop and peek.
Space complexity: O(N), where N is the number of elements in the stack.