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








Demo


6
Stack 1 is full
Stack 2 is full

Complexity 
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!...

3 comments: