Stack is a linear data structure which follows the LIFO(Last In First Out) principle. That means the Item can be inserted or removed only from top of the stack.
Stack has mainly three basic operations and few of are auxiliary operations like isEmpty,size,isFull etc:
- Push: Adding an item into the top of stack. If the stack is full then this condition is said to be an Overflow condition.
- Pop:Removing an item from the top of stack. If the stack is empty, then thus condition is said to be an Underflow condition.
- Peek or Top:Returns top element of stack.
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 |
package com.kkjavatutorials.stack; import java.util.EmptyStackException; public class Stack { private int maxSixe; private int []satckArray; private int top; public Stack(int maxSixe) { super(); this.maxSixe = maxSixe; this.satckArray = new int[maxSixe]; this.top = -1; } public void push(int data) { if(isFull()) { throw new RuntimeException("Stack is full!!"); } satckArray[++top] = data; } public int pop() { if(isEmpty()) { throw new EmptyStackException(); } return satckArray[top--]; } public int peek() { if(isEmpty()) { throw new EmptyStackException(); } return satckArray[top]; } public boolean isEmpty() { return top==-1; } public boolean isFull() { return maxSixe -1 == top; } public int size() { return top+1; } } |
Client program which using Stack:
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 |
package com.kkjavatutorials.client; import com.kkjavatutorials.stack.Stack; public class ClientTest { public static void main(String[] args) { Stack stack = new Stack(5); stack.push(10); stack.push(20); stack.push(30); stack.push(40); stack.push(50); if(!stack.isFull()) { stack.push(60); } System.out.println(stack.isFull()); System.out.println(stack.isEmpty()); System.out.println(stack.peek()); System.out.println(stack.pop()); System.out.println(stack.size()); } } |
output of the program:
true
false
50
50
4
You May Also Like:
How to implement LRU Cache in Java?
What will happen if in a try block we throw an exception but in the finally block we return a int value?
Adding two numbers without using arithmetic operators?
Thanks for visiting the blog. If you have any doubts or suggestions to make please drop a comment.