# Stack implementation in Java

March 12, 2013 6 Comments

Stacks operate in LIFO model.

Stack plays vital role in many data structures, some of them are

- in parsing arithmetic expressions
- to help traverse nodes of binary tree
- searching vertices of a graph
- in java, every method’s return type and arguments are pushed on to a stack and when method returns they are popped off.

Efficiency of stack is that it performs **push and pop operations in O(1) complexity.**

package algorithm.stack; /** * @author ntallapa * */ public class TNStack { private int size; private int[] stackArr; private int top = -1; public TNStack(int size) { this.size = size; stackArr = new int[size]; } /** * increment the ctr and push element into stack * @param i element to be pushed */ public void push(int i) { top++; System.out.println("Pushing "+i); stackArr[top] = i; } /** * pop the element from stack and decrement the ctr * @return the popped element */ public int pop() { int i = stackArr[top]; top--; System.out.println("Popping "+i); return i; } public int peek() { System.out.println("Peek "+stackArr[top]); return stackArr[top]; } public boolean isFull() { return (top == size-1); } public boolean isEmpty() { return (top == -1); } } package algorithm.stack; /** * @author ntallapa * */ public class TNStackClient { /** * @param args */ public static void main(String[] args) { TNStack tns = new TNStack(3); // push some elements if(!tns.isFull()) tns.push(4); if(!tns.isFull()) tns.push(5); if(!tns.isFull()) tns.push(3); if(!tns.isFull()) tns.push(6); else System.out.println("Stack is full, cannot push element"); // pop some elements if(!tns.isEmpty()) tns.pop(); if(!tns.isEmpty()) tns.pop(); if(!tns.isEmpty()) tns.pop(); if(!tns.isEmpty()) tns.pop(); else System.out.println("Stack is empty, cannot pop element"); //reinsert to verify peek method if(!tns.isFull()) tns.push(6); // peek couple of times; result should be same tns.peek(); tns.peek(); } }

**Output:**

Pushing 4

Pushing 5

Pushing 3

Stack is full, cannot push element

Popping 3

Popping 5

Popping 4

Stack is empty, cannot pop element

Pushing 6

Peek 6

Peek 6

Pingback: algorithm to reverse a string in O(n/2) complexity | java tech stack

Pingback: decimal to binary/octa/hexadecimal conversion | java tech stack

does algorithm.stack in present in java jdk is it inbuilt???

yes it is @java.util.Stack

how do we implement if we need to dynamically deallocate memory when pop() is used?

I think in push() and pop() method you need to check for isFull() or isEmpty() to ensure when popping out an element from stack should not throw “ArrayIndexOutOfBoundException”