Mega Code Archive

 
Categories / Java Tutorial / Collections
 

A stack allows access to only one data item

Push: To insert a data item on the stack Pop : To remove a data item from the top of the stack 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