A singly linked list makes a stack that can grow without limit. The head of the list is the top of the stack, because a singly linked list can add and remove nodes at its head in O(1) time.
A stack can be built on an array or on a linked list. This page shows the linked-list version; the array version has its own tutorial.
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 {
// One element of the stack
static class Node {
int data; // value stored in the node
Node next; // the node below this one
Node(int data) {
this.data = data;
}
}
private Node top; // top of the stack; null when the stack is empty
// Push: the new node goes in front of the current top
public void push(int data) {
Node newNode = new Node(data);
newNode.next = top; // works for an empty stack too (top is null)
top = newNode;
System.out.println(data + " pushed to the stack");
}
// Pop: remove the top node and report its value
public void pop() {
if (top == null) {
System.out.println("Stack is empty");
return;
}
int popped = top.data;
top = top.next; // the node below becomes the new top
System.out.println(popped + " popped from the stack");
}
// Peek: show the top value without removing it
public void peek() {
if (top == null) {
System.out.println("Stack is empty");
} else {
System.out.println("Top element of stack: " + top.data);
}
}
// Print the items from top to bottom without changing the stack
public void printLinkedList() {
Node temp = top;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
public static void main(String[] args) {
StackUsingLinkedList stack = new StackUsingLinkedList();
stack.push(10);
stack.push(20);
stack.push(30);
stack.pop();
stack.peek();
stack.push(50);
stack.push(60);
stack.pop();
stack.printLinkedList();
}
}
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.