Sample source code for Stack implementation in Java
===================== MyStack.java =====================
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
public class MyStack { private static int[] stackArr = new int[5]; private static int top = -1; public void push(int element) { if (!this.isFull()) { top++; stackArr[top] = element; } else { System.out.print("\nStack Overflow!!\n"); } } public int pop() { int temp = -9999; if (!this.isEmpty()) { temp = stackArr[top]; top--; return temp; } else { System.out.print("\nStack Underflow!!\n"); return temp; } } public boolean isEmpty() { if (top == -1) { return true; } return false; } public boolean isFull() { if (top == stackArr.length - 1) { return true; } return false; } public void printStack() { System.out.print("Stack: "); for (int i = 0; i <= top; i++) { System.out.print(stackArr[i] + "\t"); } System.out.println(); } public static void main(String args[]) { MyStack myStack = new MyStack(); myStack.push(0); myStack.printStack(); myStack.push(1); myStack.printStack(); myStack.push(2); myStack.printStack(); myStack.push(3); myStack.printStack(); myStack.push(4); myStack.printStack(); myStack.push(5); myStack.pop(); myStack.printStack(); myStack.push(5); myStack.printStack(); myStack.pop(); myStack.printStack(); myStack.pop(); myStack.printStack(); myStack.pop(); myStack.printStack(); myStack.pop(); myStack.printStack(); myStack.pop(); myStack.printStack(); myStack.pop(); myStack.push(5); myStack.printStack(); } } |
NOTE: Java Collections framework implementation for Stack is here.