Java Program to Show Stack Implementation

Java Program to Show Stack Implementation

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 push method is used to add a new item to the top of the stack.
  • It creates a new node (newTop) and assigns the value N to its item 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 the top 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.
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;
}

}

 

M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post