Stack
Stack
What is a stack?
A stack is a type of data structure that organizes items in a way that the last item
added is the first one to be taken out. This is known as the Last In, First Out
principle or known as the LIFO principle.
It was basic, you can think of it like a stack of plates, you can only add or take
away the top plate. If you want to remove a plate from the bottom, you have to take
off the plates on top first. This structure is useful in many programming situations,
like managing tasks and storing data temporarily.
“The methods of the Stack class from the java.util package are used to implement
stacks in Java.”
What does it mean? This means that in Java, you can use the Stack class from the
java.util package to create and manage stacks easily. It provides built-in methods
for common tasks like adding and removing items, so you don't have to create a
stack from scratch.
There are two (2) main stack operations are the following:
1. Push
2. Pop
Push
The push operation adds an element to the top of the stack. When an element is
pushed onto the stack, it becomes the new top item, and any previously existing
elements are now below it.
Pop
The pop operation removes the top element from the stack. When an element is
popped, it is removed from the stack and returned to the caller, making the next
element below it the new top item.
Pop Code
Other stack operations:
1. Peek
2. Test whether stack is empty
Peek
The peek operation allows users to view the top element of the stack without
removing it. This is useful when you need to see the most recently added item but
do not want to modify the stack’s contents.
Peek Code
Test whether stack is empty
This operation checks whether the stack contains any elements. It is essential for
avoiding errors when attempting to pop or peek from an empty stack, as such
operations would typically lead to exceptions or undefined behavior.