This is a simple Java program to demonstrate the Stack data structure implementation. This code provides a simple implementation of a stack with basic operations (push
, pop
, and isEmpty
). Understanding how a stack works is fundamental, and this code demonstrates the concept in a straightforward manner. Additionally, it introduces the concept of an inner class (Node
), which is commonly used in data structure implementations. Internally, the stack is implemented as a linked list.
push Method:

Discover the mind behind the innovations – Elon Musk by Walter Isaacson, now on Audible. Dive into the life of a visionary shaping our future!
View on Amazon
- The
push
method is used to add a new item to the top of the stack. - It creates a new node (
newTop
) and assigns the valueN
to itsitem
field. - The
next
field of the new node is set to the current top of the stack. - Finally, the
top
reference is updated to the new node.
pop Method:
- The
pop
method removes the top item from the stack and returns its value. - It first retrieves the value of the top item (
topItem
), updates thetop
reference to the next node in the stack, and then returns the retrieved value. - Note: This method does not handle the case where an attempt is made to pop from an empty stack. It would be better to throw a specific exception in that case.