-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathKStackInArray.java
49 lines (48 loc) · 1.25 KB
/
KStackInArray.java
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
package SummerTrainingGFG.Stack;
/**
* @author Vishal Singh
*/
public class KStackInArray {
static class KStack{
int[] arr;
int[] top;
int[] next;
int k, capacity, freeTop;
KStack(int k1, int n){
k = k1;
capacity = n;
arr = new int[capacity];
top = new int[k];
next = new int[capacity];
freeTop = 0;
for (int i = 0; i < capacity-1; i++) {
next[i] = i+1;
}
next[capacity-1] = -1;
}
void push(int x, int stackNumber){
int i = freeTop;
freeTop = next[i];
next[i] = top[stackNumber];
top[stackNumber] = i;
arr[i] = x;
}
int pop(int stackNumber){
int i = top[stackNumber];
top[stackNumber] = next[i];
next[i] = freeTop;
freeTop = i;
return arr[i];
}
}
public static void main(String[] args) {
KStack kStack = new KStack(4,4);
kStack.push(101,0);
kStack.push(211,1);
kStack.push(325,2);
kStack.push(444,3);
for (int i = 0; i < 4; i++) {
System.out.println(kStack.pop(i));
}
}
}