数据结构-两个栈实现一个队列和两个队列实现一个栈

两个栈实现一个队列

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
import java.util.Stack;
/**
* Created by cdx0312
* 2018/4/13
*/
public class TwoStackImpQueue {
private Stack<Integer> stack1 = new Stack<>();
private Stack<Integer> stack2 = new Stack<>();
public void push(int node) {
stack1.push(node);
}
public Integer pop() {
if (stack2.size() <= 0) {
while (stack1.size() > 0) {
stack2.push(stack1.pop());
}
}
if (stack2.isEmpty()) {
try {
throw new Exception("queue is empty");
} catch (Exception e){
e.printStackTrace();
}
}
return stack2.pop();
}
}

两个队列实现一个栈

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
import java.util.LinkedList;
import java.util.Queue;
/**
* Created by cdx0312
* 2018/4/13
*/
public class TwoListImpStack {
private Queue<Integer> list1 = new LinkedList<>();
private Queue<Integer> list2 = new LinkedList<>();
public void push(int node) {
if (list1.isEmpty() && list2.isEmpty()){
list1.add(node);
} else if (list1.isEmpty()) {
list2.add(node);
} else {
list2.add(node);
}
}
public Integer pop() {
if (list1.isEmpty() && list2.isEmpty()){
try {
throw new Exception("stack is Empty!");
} catch (Exception e) {
e.printStackTrace();
}
} else if (list1.isEmpty()) {
while (list2.size() > 1) {
list1.add(list2.poll());
}
return list2.poll();
} else {
while (list1.size() > 1) {
list2.add(list1.poll());
}
return list1.poll();
}
return null;
}
}
Donate comment here