-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoStackQue.java
More file actions
101 lines (94 loc) · 2.02 KB
/
TwoStackQue.java
File metadata and controls
101 lines (94 loc) · 2.02 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package lintCode;
import java.util.Stack;
public class TwoStackQue {
private Stack<Integer> st1;
private Stack<Integer> st2;
boolean flag = false;
public TwoStackQue() {
st1 = new Stack<>();
st2 = new Stack<>();
}
public void push(int element) {
if(flag == false){
if(st1.isEmpty() && st2.isEmpty()){
st1.push(element);
}else if(!st1.isEmpty()){
st1.push(element);
}else if(!st2.isEmpty()){
st2.push(element);
}
}else{
flag = false;
if(st1.isEmpty() && st2.empty()){
st1.push(element);
}else if(!st1.isEmpty()){
while(!st1.isEmpty()){
st2.push(st1.pop());
}
st2.push(element);
}else if(!st2.isEmpty()){
while(!st2.isEmpty()){
st1.push(st2.pop());
}
st1.push(element);
}
}
}
public int pop() {
if(flag == true){
if(st1.isEmpty() && st2.isEmpty()){
}else if(!st1.isEmpty()){
return st1.pop();
}else if(!st2.isEmpty()){
return st2.pop();
}
}else{
flag = true;
if(!st1.isEmpty()){
while(!st1.isEmpty()){
st2.push(st1.pop());
}
return st2.pop();
}else if(!st2.isEmpty()){
while(!st2.isEmpty()){
st1.push(st2.pop());
}
return st1.pop();
}
}
return 0;
}
public int top() {
if(flag == true){
if(st1.isEmpty() && st2.isEmpty()){
}else if(!st1.isEmpty()){
return st1.peek();
}else if(!st2.isEmpty()){
return st2.peek();
}
}else{
flag = true;
if(!st1.isEmpty()){
while(!st1.isEmpty()){
st2.push(st1.pop());
}
return st2.peek();
}else if(!st2.isEmpty()){
while(!st2.isEmpty()){
st1.push(st2.pop());
}
return st1.peek();
}
}
return 0;
}
public static void main(String[] args) {
TwoStackQue s = new TwoStackQue();
s.push(1);
s.pop();
s.push(2);
s.push(3);
s.top();
s.pop();
}
}