代码随想录第十天|
Leetcode 232. 用栈实现队列
题目链接: 用栈实现队列
自己的思路:使用两个栈来模拟队列,栈s_in来进行输入,栈s_out来进行输出;难点在于pop和peek处,当s_out为空的时候,将s_in中的元素都放到s_out中
正确思路:
代码:
class MyQueue {
Stack<Integer> s_in;
Stack<Integer> s_out;
public MyQueue() {
s_in = new Stack<>();
s_out = new Stack<>();
}
public void push(int x) {
s_in.push(x);
}
public int pop() {
move();
return s_out.pop();
}
public int peek() {
move();
return s_out.peek();
}
public boolean empty() {
return s_in.isEmpty()&&s_out.isEmpty();
}
public void move(){
if (!s_out.isEmpty()){
}else{
while(!s_in.isEmpty()){
s_out.push(s_in.pop());
}
}
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
Leetcode 225. 用队列实现栈
题目链接: 用队列实现栈
自己的思路:没想出来
正确思路:使用两个队列来实现栈的操作;实质是一个队列的操作,另一个队列是辅助队列,辅助队列用于反转目标队列的元素顺序:先将元素加入到辅助队列中,然后再将目标队列中的元素加入到辅助队列中,最后再交换两个队列即可。
代码:
class MyStack {
Queue<Integer> q1;
Queue<Integer> q2;
public MyStack() {
q1 = new LinkedList<>();
q2 = new LinkedList<>();
}
public void push(int x) {
q2.offer(x);
while(!q1.isEmpty()){
q2.offer(q1.poll());
}
Queue<Integer> temp = q1;
q1 = q2;
q2 = temp;
}
public int pop() {
return q1.poll();
}
public int top() {
return q1.peek();
}
public boolean empty() {
return q1.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/