法一
/**
* 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();
*/
public class Solution225 {
private Queue<Integer> q1; //输入队列
private Queue<Integer> q2; //输出队列
public Solution225() {
q1 = new LinkedList<>();
q2 = new LinkedList<>();
}
public void push(int x) {
q1.offer(x);
while(!q2.isEmpty()){ // 将q2队列中元素全部转给q1队列
q1.offer(q2.poll());
}
Queue tmp = q1; // 交换q1和q2,使得q1队列没有在push()的时候始终为空队列
q1 = q2;
q2 = tmp;
}
public int pop() {
return q2.poll();
}
public int top() {
return q2.peek();
}
public boolean empty() {
return q2.isEmpty();
}
}
本地测试
/**
* 225. 用队列实现栈
*/
lay.showTitle(225);
Solution225 sol225 = new Solution225();
sol225.push(1);
sol225.push(2);
System.out.println(sol225.top());
System.out.println(sol225.pop());
System.out.println(sol225.empty());
版权声明:本文为qq_41829337原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。