In this post we’ll see an implementation of Stack in Java using array. Stack can also be implemented using Linked list.
- Refer Stack Implementation in Java Using Linked List to see how to implement Stack using Linked List in Java.
Stack data structure
A stack is a Last In First Out (LIFO) data structure. In a stack items are both inserted and removed from the top and you have access to a single data item; that is the last item inserted. Once that is retrieved then only you can access the next item.
Following image shows the items in a Stack.
Operations in a Stack
Mainly following three operations are implemented for a Stack-
- push- To insert an item on the stack.
- pop- To remove an item from the top of the stack.
- peek- Read value from the top of the stack without removing it.
Java program for Stack
public class Stack { private int maxSize; private int[] stackArray; private int top; Stack(int max){ this.maxSize = max; stackArray = new int[maxSize]; top = -1; } public void push(int item){ if(top >= maxSize - 1){ System.out.println("Stack already full.."); return; } // increment top then insert item stackArray[++top] = item; } public int pop(){ if(top < 0){ throw new RuntimeException("Stack is Empty"); } // retrieve item then decrement return stackArray[top--]; } public int peek(){ // return top item value return stackArray[top]; } public boolean isEmpty(){ return (top < 0); } public boolean isFull(){ return (top == maxSize - 1); } public static void main(String[] args) { Stack stack = new Stack(20); stack.push(1); stack.push(2); stack.push(3); stack.push(4); stack.push(5); System.out.println("Item popped- " + stack.pop()); System.out.println("Item popped- " + stack.pop()); while(!stack.isEmpty()){ System.out.println("Item popped- " + stack.pop()); } } }
Output
Item popped- 5 Item peeked- 4 Item popped- 4 Item popped- 3 Item popped- 2 Item popped- 1
Performance of stack
In stack items can be inserted and removed in O(1) time.
That's all for this topic Stack Implementation in Java Using Array. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-
No comments:
Post a Comment