LeetCode 232 栈做的队列
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-queue-using-stacks
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
同队列做的栈,比较简单。
import java.util.Stack;
/**
* leetcode 232 用栈实现队列
*/
public class MyQueue {
private Stack<Integer> s1;
private Stack<Integer> s2;
public MyQueue() {
s1 = new Stack<>();
s2 = new Stack<>();
}
/**
* 思路:栈是先进后出,同MyStack那题,这里用栈来实现队列的
* 先进先出。先将s1中元素push入s2,再将x push入s2。完成
* 后,将s2的元素重新push回s1,即完成元素的先进先出顺序
* @param x
*/
public void push(int x) {
if (s1.isEmpty()) {
s1.push(x);
}
else {
while (! s1.isEmpty()) {
s2.push(s1.peek());
s1.pop();
}
s2.push(x);
while (! s2.isEmpty()) {
s1.push(s2.peek());
s2.pop();
}
}
}
public int pop() {
return s1.pop();
}
public int peek() {
return s1.peek();
}
public boolean empty() {
return s1.isEmpty();
}
/* // 测试
public static void main(String[] args) {
MyQueue myQueue = new MyQueue();
myQueue.push(1);
myQueue.push(2);
System.out.println(myQueue.pop());
myQueue.push(3);
System.out.println(myQueue.pop());
}*/
}