Implement 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.
Example:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false
使用堆栈实现队列的以下操作。
push(x) - 将元素x推送到队列的后面。 pop() - 从队列前面删除元素。 peek() - 获取前面的元素。 empty() - 返回队列是否为空。 例:
MyQueue queue = new MyQueue();
queue.push(1); queue.push(2); queue.peek(); //返回1 queue.pop(); //返回1 queue.empty(); //返回false
Notes:**
- You must use only standard operations of a stack – which means only
push 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).
您必须仅使用堆栈的标准操作 - 这意味着只能从顶部切换到顶部,查看/弹出,大小,并且空操作是有效的。 根据您的语言,本机可能不支持堆栈。 您可以使用列表或双端队列(双端队列)来模拟堆栈,只要您只使用堆栈的标准操作即可。 您可以假设所有操作都是有效的(例如,不会在空队列上调用pop或Peek操作)。 公认