Stack Implementation in Java

An object of type IntStack is a stack of real numbers, with the standard stack operations push(int N), pop(), and isEmpty(). A makeEmpty() operation is also provided to remove all items from the stack.

Internally, the stack is implemented as a linked list.

*     MYCPLUS Sample Code -     *
*                                                     *
*   This code is made available as a service to our   *
*      visitors and is provided strictly for the      *
*               purpose of illustration.              *
*                                                     *
* Please direct all inquiries to saqib at *

public class NumberStack {

   private static class Node {
          // An object of type Node holds one of the
          // items on the stack;
      double item;
      Node next;

   private Node top;  // Pointer to the Node that is at the top of
                      //   of the stack.  If top == null, then the
                      //   stack is empty.

   public void push( double N ) {
          // Add N to the top of the stack.
      Node newTop = new Node();
      newTop.item = N; = top;
      top = newTop;

   public double pop() {
         // 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.)
      double topItem = top.item;
      top =;
      return topItem;

   public boolean isEmpty() {
         // Returns true if the stack is empty.  Returns false
         // if there are one or more items on the stack.
      return top == null;

} // end class NumberStack

Leave a Reply