Wednesday, June 25, 2014

Implementation of Two Stacks with one Array in Java

Two Stacks with one Array in Java
This is the continuation of previous post on Array implementation of stack in java. In this post, we implements 2 stacks using one array.

While implementing stack using array we took one index which first initially point to -1, In this case of 2 stacks we take two index one point to -1 and other point to the end of the array i.e, size of the array.

Algorithms :

  • Start with two indexes one at the left and other at the right end of the array.
  • Left index simulate the first stack and second index simulate the right stack.
  • If we want to put the element in the first stack then put the element at the left index. Similarly, if we want to put the element in the second stack then put the element at the right index.
  • First stack grow towards left and second stack grow towards left.

Custom Stack Exception Class

Stack Class


Stack 1 is full
Stack 2 is full

Space Complexity : O(1)
Time Complexity : Push and Pop operation O(1)

Download Code : StackException TwoStackWithArray TwoStackWithArrayDemo

If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...


  1. Thanks For Sharing the Sample Coding for Freshers,

  2. The function pop() should only require StackId as an input Parameter.

  3. I am technology Enthusiast. Your blog is really awesome, attractive and impressive. I like the way you think. it is very useful for Java SE & Java EE Learners. Your article adds best knowledge to our Java Online Training in India. or learn thru Java Online Training in India Students. or learn thru JavaScript Online Training in India. Appreciating the persistence you put into your blog and detailed information you provide. Kindly keep blogging.