26 Jan 2014

Two Stacks

Problem Statement: 
    Implement two stacks in an array.

Fig: Two Stack implementation
Source Code
Solution:

 For implementing two stacks in an array efficiently we will take two TOP pointers which grow from opposite sides of the array.

PUSH , POP , PEEK takes the "StackNumber" argument which decides on which stack operation is to be performed.


 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
 
 /**
  * Push Operation
  * @param stackNum 0: 1st stack  , 1: 2nd stack
  * @param data : data to be pushed
  * @throws InterruptedException 
  */
 public void push(int stackNum, int data) throws InterruptedException{
  Thread.sleep(10);
  if(stackNum==1){
   pushToStack1(data);
  }
  else if(stackNum==2)
   pushToStack2(data);
  else
   System.out.println("Invalid Stack Number");
 }
 
 public int pop(int stackNum) throws InterruptedException{
  Thread.sleep(10);
  if(stackNum==1)
   return popFromStack1();
  else if (stackNum==2)
   return popFromStack2();
  else{
   System.err.println("Invalid Stack");
   return -1;
  }
 }
 
 public int peek(int stackNum) throws InterruptedException{
  Thread.sleep(10);
  if(stackNum==1)
   return peekFromStack1();
  else if (stackNum==2)
   return peekFromStack2();
  else{
   System.err.println("Invalid Stack");
   return -1;
  }
 }

Please comment and post your suggestions.
Happy Coding!!:)


No comments:

Post a Comment