-
Notifications
You must be signed in to change notification settings - Fork 124
Expand file tree
/
Copy pathTwoStacks.java
More file actions
52 lines (44 loc) · 858 Bytes
/
TwoStacks.java
File metadata and controls
52 lines (44 loc) · 858 Bytes
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
package stackProblems2;
public class TwoStacks {
int a[];
int top1, top2;
public TwoStacks(int capacity) {
a = new int[capacity];
top1 = -1;
top2 = capacity;
}
void push1(int data) throws Exception {
if(top1+1<top2) { // overflow check
top1++;
a[top1] = data;
} else {
throw new Exception("Stack array is Full");
}
}
void push2(int data) throws Exception {
if(top1+1<top2) {
top2--;
a[top2] = data;
} else {
throw new Exception("Stack array is Full");
}
}
int pop1() throws Exception {
if(top1 > -1) { //underflow check
int res = a[top1];
top1--;
return res;
} else {
throw new Exception("Stack1 is Empty");
}
}
int pop2() throws Exception {
if(top2 < a.length) {
int res = a[top2];
top2++;
return res;
} else {
throw new Exception("Stack2 is Empty");
}
}
}