Stack is a commonly used Data Structure in programming. You can imaging a Programming Stack as similar to any real world stack. A stack of chairs, a stack of cards. What goes inside the stack first comes out last, Or what goes in a stack last comes out first.
Thus an Stack is a Last in First Out (LIFO) Structure of Data
Let's get familiar with certain programming terms before diving into the implementation. When we put a new data element in a Stack we are doing a push, when we get the element from the stack we are doing a pull, When we are checking the top most element of stack without removing it from stack, its a peek.
Implementation in Java
package info.FiveBalloons.Examples; import java.util.Arrays; public class TheStack { private String[] stackArray; private int stackSize; private int topOfStack = -1; TheStack(int stackSize){ this.stackSize = stackSize; stackArray = new String[this.stackSize]; Arrays.fill(stackArray, "-1"); } //Push operation public void push(String data){ if(topOfStack +1 < stackSize){ topOfStack++; stackArray[topOfStack] = data; System.out.println("PUSH: New data element "+data+" is pushed into stack"); }else{ System.out.println("Stack is full"); } } //Pop Operation public String pop(){ if(topOfStack >= 0){ System.out.println("POP: top data element "+stackArray[topOfStack]+" is removed from stack"); stackArray[topOfStack] = "-1"; return stackArray[topOfStack--]; }else{ System.out.println("Sorry but the stack is empty"); return "-1"; } } // Peek operation public String peek() { System.out.println("PEEK: " + stackArray[topOfStack] + " is at the top of the Stack."); return stackArray[topOfStack]; } // Using our Stack public static void main(String[] args ) { TheStack theStack = new TheStack(10); theStack.push("5Balloons"); theStack.push("Programming"); theStack.push("Tutorials"); theStack.peek(); theStack.pop(); theStack.pop(); theStack.pop(); } }
This program will produce the following output.
PUSH: New data element Programming is pushed into stack
PUSH: New data element Tutorials is pushed into stack
PEEK: Tutorials is at the top of the Stack.
POP: top data element Tutorials is removed from stack
POP: top data element Programming is removed from stack
POP: top data element 5Balloons is removed from stack