Stack using LinkedList class in Java
Stack is a linear data structure which follows the Last-In-First-Out (LIFO) approach, where the last element inserted is the first one to be removed.
In this post, we’ll see how to implement a stack using the LinkedList class. Java provides the LinkedList class as part of the Java Collections Framework. For an overview of the Java Collections Framework, check out my post Overview of the Java Collections Framework.
Some important methods provided by the LinkedList class are:
- push(E element)
- pop()
- peek()
- isEmpty()
LinkedList class permits all elements, including null
. But it is not recommended to insert nulls because null
is used as a special return value by various methods to indicate that the deque is empty.
The following example demonstrates how to implement a stack using the LinkedList class.
Example
Output
Let us look closely at each method used in the above program.
Methods
1) push(E element)
This method pushes an element onto the stack represented by this list. In other words, it inserts the element at the front of this list.
Consider a stack with the following elements from top: “Banana” “Apple”
This method pushes the string “Orange” to the top of the stack. Now, the elements in the stack are: “Orange” “Banana” “Apple”
2) pop()
This method pops an element from the stack represented by this list. In other words, it removes and returns the first element of this list.
If the stack is empty, a ‘NoSuchElementException’
exception is thrown.
This method removes and returns the string “Orange” which is at the top of the stack.
3) peek()
It retrieves, but does not remove, the head (first element) of this list. As the name indicates, it is similar to peeking at the top of the stack.
This call to the method returns the string “Banana” which is at the top of the stack, but doesn’t remove it from the stack.
4) isEmpty()
This method tests if the stack is empty. It returns true if the stack is empty or false otherwise.
The above while
loop continues to execute until the stack is empty.
Now since you know how to implement a stack using the LinkedList class, check out other ways to create a stack: