栈实现队列
题目链接
https://programmercarl.com/0232.%E7%94%A8%E6%A0%88%E5%AE%9E%E7%8E%B0%E9%98%9F%E5%88%97.html
思路
两个栈,一个入栈,一个出栈
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() {
xx();
return stackOut.pop();
}
public int peek() {
xx();
return stackOut.peek();
}
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
private void xx() {
if(stackOut.isEmpty()) {
while(!stackIn.isEmpty()) {
stackOut.push(stackIn.pop());
}
}
}
}
队列实现栈
题目链接
https://programmercarl.com/0225.%E7%94%A8%E9%98%9F%E5%88%97%E5%AE%9E%E7%8E%B0%E6%A0%88.html
思路
class MyStack {
private Queue<Integer> queue;
public MyStack() {
queue = new LinkedList();
}
public void push(int x) {
queue.add(x);
}
public int pop() {
xx();
return queue.poll();
}
public int top() {
xx();
int a = queue.poll();
queue.add(a);
return a;
}
private void xx() {
int size = queue.size();
size--;
while(size > 0){
queue.add(queue.poll());
size--;
}
}
public boolean empty() {
return queue.isEmpty();
}
}
网友评论