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)
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.
Let us look closely at each method used in the above program.
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”
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.
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.
This method tests if the stack is empty. It returns true if the stack is empty or false otherwise.
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: