描述

用栈实现队列232

分析

实现

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
import java.util.Scanner;
import java.util.Stack;

//用栈实现队列232
public class ImplementQueueUsingStacks232 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

MyQueue obj = new MyQueue();
System.out.print("请输入入队数字:");
int x = input.nextInt();
obj.push(x);
obj.push(66);
int param_2 = obj.pop();
System.out.println("\npop为: " + param_2);
int param_3 = obj.peek();
System.out.println("peek为: " + param_3);
boolean param_4 = obj.empty();
System.out.println("链表是否为空:" + param_4);
}
}

//队列
class MyQueue {
Stack<Integer> stackIn;
Stack<Integer> stackOut;

public MyQueue() {
stackIn = new Stack<>();
stackOut = new Stack<>();
}

public void push(int x) {
stackIn.push(x);
}

public int pop() {
in2Out();
return stackOut.pop();
}

public int peek() {
in2Out();
return stackOut.peek();
}

public boolean empty() {
return stackOut.isEmpty() && stackIn.isEmpty();
}

public void in2Out(){
if (!stackOut.isEmpty()) {
return;
}
while(!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
}

总结