-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoStacks.java
More file actions
63 lines (53 loc) · 1.26 KB
/
TwoStacks.java
File metadata and controls
63 lines (53 loc) · 1.26 KB
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
61
62
63
package Stacks;
public class TwoStacks {
int size;
int top1, top2;
int[] arr;
TwoStacks(int n) {
arr = new int[n];
size = n;
top1 = -1;
top2 = size;
}
public static void main(String[] args) {
TwoStacks ts = new TwoStacks(5);
ts.push1(5);
ts.push2(10);
ts.push2(15);
ts.push1(11);
ts.push1(7);
System.out.println("Popped element from" + " stack1 is " + ts.pop1());
ts.push2(40);
System.out.println("Popped element from" + " stack2 is " + ts.pop2());
}
void push1(int x) {
if (top2 - top1 > 1) {
arr[++top1] = x;
} else {
System.out.println("Stack Overflow");
}
}
void push2(int x) {
if (top2 - top1 > 1) {
arr[--top2] = x;
} else {
System.out.println("Stack Overflow");
}
}
int pop1() {
if (top1 >= 0) {
return arr[top1--];
} else {
System.out.println("Stack Underflow");
return -1;
}
}
int pop2() {
if (top2 < size) {
return arr[top2++];
} else {
System.out.println("Stack Underflow");
return -1;
}
}
}