232.用栈实现队列
题解及想法
class MyQueue {
Stack<Integer> stack1;
Stack<Integer> stack2;
public MyQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void push(int x) {
stack1.push(x);
}
public int pop() {
dumpstackIn();
return stack2.pop();
}
public int peek() {
dumpstackIn();
return stack2.peek();
}
public boolean empty() {
return stack1.isEmpty() && stack2.isEmpty();
}
private void dumpstackIn(){
if(!stack2.isEmpty()){
return;
}
while (!stack1.isEmpty()){
stack2.push(stack1.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();
*/
225. 用队列实现栈
题解及想法
class MyStack {
Queue<Integer> queue1;
public MyStack() {
queue1 = new LinkedList<>();
}
public void push(int x) {
queue1.offer(x);
int size = queue1.size();
size--;
while (size-- > 0){
queue1.offer(queue1.poll());
}
}
public int pop() {
return queue1.poll();
}
public int top() {
return queue1.peek();
}
public boolean empty() {
return queue1.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();
*/
返回该题
力扣 LeetCode