关于LeetCode中Implement Queue using Stacks一题的理解

时间:2023-01-20 17:36:16

题目如下:

mplement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.
Notes:
  • You must use only standard operations of a stack -- which means onlypush to top,peek/pop from top,size, andis empty operations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

class MyQueue {
private Stack s;
private Stack temp;
public MyQueue(){
s = new Stack<Integer>();
temp = new Stack<Integer>();
}
// Push element x to the back of queue.
public void push(int x) {
s.push(x);
}

// Removes the element from in front of queue.
public void pop() {
if(temp.empty()){
while(!s.empty()){
temp.push(s.pop());
}
}
temp.pop();
}

// Get the front element.
public int peek() {
int result = 0;
if(temp.empty()){
while(!s.empty()){
temp.push(s.pop());
}
}
result = (int)temp.peek();
return result;
}
// Return whether the queue is empty.
public boolean empty() {
if(s.empty()&&temp.empty()){
return true;
}else{
return false;
}
}
}
    题目的意思就是用栈去实现一个队列,只能用栈的一些基本操作,如pop,push,peek,empty等。还是比较容易实现的,已Accepted的代码在上面。

    这道题也是有Editorial Solution的,地址在这里:https://leetcode.com/articles/implement-queue-using-stacks/ 。里面说了两种方式,比较详细,而且有图,容易理解。