The stack is a linear data structure. It works under LIFO(Last In First Out mechanism) and it has 3 basic operations: Pop(), Push(), and peek(). Push and Pop operations can be performed only at one end that is called top. peek() operation is to display elements in a stack.
Below is the JAVA implementation of STACK. The datatype we will store in Stack is String
When Stack is full, it is called 'OVERFLOW', and when the stack is empty, we call this 'UNDERFLOW'
public class StackOfString { int top = -1; String[] myStack; public StackOfString() { this.myStack = new String[5]; } public void pop() { if (top != -1) { System.out.println("Item to be Poped: " + myStack[top]); myStack[top] = null; top -= 1; } else { System.out.println("Stack is UNDERFLOW!!!"); } } public void push(String str) { if (isFull()) { top += 1; myStack[top] = str; }else { System.out.println("Stack is OVERFLOW!!!"); } } public boolean isFull() { if (top < (myStack.length -1)) { return true; } else { return false; } } public void peek() { for (String string : myStack) { if (string != null) System.out.println(string); } }}
public class Client { public static void main(String[] args) { // TODO Auto-generated method stub StackOfString stackOfString = new StackOfString(); stackOfString.pop(); stackOfString.push("A"); stackOfString.push("B"); stackOfString.push("C"); stackOfString.push("D"); stackOfString.push("E"); stackOfString.peek(); stackOfString.push("F"); stackOfString.pop(); stackOfString.pop(); stackOfString.pop(); stackOfString.pop(); stackOfString.pop(); stackOfString.pop(); }}
This is the output:
