26 Jan 2014

Three Stacks

Problem Statement:
    Implement three stacks in a single array.
Fig: Implement three stacks in a given array
Source Code
Solution:
The concept is to divide the given array into three parts and using auxiliary space to store status of "Top" pointer of each stack.

Push and Pop operation accepts an extra argument , which specifies on which stack the operation is to be performed.

Below is the implementation  of PUSH, POP and PEEK subroutines.


 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
57
58
59
60
 private int stackSize=5;
 private int[] tops={-1,-1,-1};
 private int[] arr=new int[stackSize * 3];

 /**
  * Push operation
  * @param stackNum : specifies the stack number
  * @return: insertion status
  * @throws InterruptedException 
  */
 public boolean push(int stackNum, int item) throws InterruptedException{
  int index= stackNum * stackSize + tops[stackNum] + 1;
  if(tops[stackNum] < stackSize -1 ){
   tops[stackNum]++;
   arr[index]=item;
   Thread.sleep(10);
 System.out.println(Arrays.toString(arr));
   return true;
  }
  else{
   System.err.println("Stack Full");
   return false;
  }
 } 

 /**
  * Pop operation
  * @param stackNum: specifies the stack number
  * @return the poped item
  * @throws InterruptedException 
  */
 public int pop(int stackNum) throws InterruptedException{

  if(tops[stackNum]==-1)  {
   System.err.println("Stack is Empty");
   return -1;
  }
  int index= stackNum * stackSize + tops[stackNum];
  tops[stackNum]--;
  int item= arr[index];
  arr[index]=0;
  Thread.sleep(10);
  System.out.println(Arrays.toString(arr));
  return item;
 }

 /**
  * Peek operation
  * @param stackNum: specifies the stack number
  * @return top element of the specified stack
  */
 public int peek(int stackNum){
  if(tops[stackNum]==-1)  {
   System.out.println("Stack is Empty");
   return -1;
  }

  int index= stackNum * stackSize + tops[stackNum];
  return arr[index];
 }

Happy Coding !! :)

No comments:

Post a Comment