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:
- The
pushmethod is used to add a new item to the top of the stack. - It creates a new node (
newTop) and assigns the valueNto itsitemfield. - The
nextfield of the new node is set to the current top of the stack. - Finally, the
topreference is updated to the new node.
pop Method:
- The
popmethod removes the top item from the stack and returns its value. - It first retrieves the value of the top item (
topItem), updates thetopreference 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.
public class NumberStack {
private static class Node {
// An object of type Node holds one of the
// items on the stack;
double item;
Node next;
}
// Pointer to the Node that is at the top of
// of the stack. If top == null, then the
// stack is empty.
private Node top;
// Add N to the top of the stack.
public void push( double N ) {
Node newTop = new Node();
newTop.item = N;
newTop.next = top;
top = newTop;
}
// Remove the top item from the stack, and return it.
// Note that this routine will throw a NullPointerException
// if an attempty is made to pop an item from an empty
// stack. (It would be better style to define a new
// type of Exception to throw in this case.)
public double pop() {
double topItem = top.item;
top = top.next;
return topItem;
}
// Returns true if the stack is empty. Returns false
// if there are one or more items on the stack.
public boolean isEmpty() {
return top == null;
}
}



