232.用栈实现队列
思路:
创建两个栈,In负责接收,Out负责弹出。在弹出之前需要保证Out中有元素,有则直接弹出,没有就将In中的元素全部压入Out中。
代码:
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() {
process();
return stackOut.pop();
}
public int peek() {
process();
return stackOut.peek();
}
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
private void process(){
if(!stackOut.isEmpty()){
return;
}
while(!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
}
需要注意的点:
1、pop()为返回第一个元素并移除,peek()只返回不移除。
2、pop()和peek()在out栈中弹出结果前都需要进行一步处理。
225. 用队列实现栈
思路:
队列先进先出,所以要让新添加的元素放在队列最前方以实现栈的功能。
代码:
class MyStack {
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
queue.offer(x);
int size = queue.size();
//将压入的元素放在队列第一位(将其前面的元素弹出并放到队列后)
for(int i = 0; i < size - 1; i++){
queue.offer(queue.poll());
}
}
public int pop() {
return queue.poll();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.isEmpty();
}
}
需要注意的点:
1、LinkedList类实现了Queue接口,因此我们可以把LinkedList当成Queue来用。
2、队列常规操作: