LinkedList as Stack


In Java, Stack
is a subclass of Vector
, but it can be implemented using a LinkedList
for better performance in some cases. Here's a practical way to use LinkedList
as a stack:
Why Use LinkedList for Stack?
LinkedList
provides efficientaddFirst()
andremoveFirst()
methods, which can mimic stack operations efficiently.Unlike
Stack
, which is synchronized and less performant,LinkedList
offers a more lightweight alternative.
Example Code Using LinkedList as a Stack
import java.util.LinkedList;
public class LinkedListAsStack {
public static void main(String[] args) {
LinkedList<String> stack = new LinkedList<>();
// Push operation (addFirst)
stack.addFirst("A");
stack.addFirst("B");
stack.addFirst("C");
System.out.println("Stack after pushes: " + stack);
// Pop operation (removeFirst)
System.out.println("Popped: " + stack.removeFirst());
// Peek operation (getFirst)
System.out.println("Peek: " + stack.getFirst());
System.out.println("Stack after operations: " + stack);
}
}
Key Operations Mapping
Push:
addFirst(E element)
Pop:
removeFirst()
Peek:
getFirst()
This approach keeps the stack operations efficient while leveraging the flexibility of LinkedList
.
Subscribe to my newsletter
Read articles from Ganti Sai Sagar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Ganti Sai Sagar
Ganti Sai Sagar
Results-driven SDET with expertise in automation frameworks, API testing, and CI/CD pipelines. Proficient in Selenium, Appium, Postman, JUnit, TestNG and Jenkins. Skilled in Java and performance testing, ensuring high-quality software delivery in Agile environments.