A stack allows access to only one data item: the last item inserted : Your Stack « Collections « Java Tutorial






  1. Push: To insert a data item on the stack
  2. Pop : To remove a data item from the top of the stack
  3. Peek: Read the value from the top of the stack without removing it.
class Stack {
  private int maxSize;

  private double[] stackArray;

  private int top;

  public Stack(int s) {
    maxSize = s;
    stackArray = new double[maxSize];
    top = -1; 
  }

  public void push(double j) {
    stackArray[++top] = j;
  }

  public double pop() {
    return stackArray[top--];
  }

  public double peek() {
    return stackArray[top];
  }

  public boolean isEmpty() {
    return (top == -1);
  }

  public boolean isFull() {
    return (top == maxSize - 1);
  }
}

public class MainClass {
  public static void main(String[] args) {
    Stack theStack = new Stack(10);
    theStack.push(20);
    theStack.push(40);
    theStack.push(60);
    theStack.push(80);

    while (!theStack.isEmpty()) {
      double value = theStack.pop();
      System.out.print(value);
      System.out.print(" ");
    }
    System.out.println("");
  }
}
80.0 60.0 40.0 20.0








9.52.Your Stack
9.52.1.A stack allows access to only one data item: the last item inserted
9.52.2.Using stack to reverse a string
9.52.3.Stack Example: Delimiter Matching
9.52.4.Demonstrating a stack implemented as a list