[Leetcode] #232 Implement Queue using Stacks

来源:互联网 发布:清楚淘宝浏览记录 编辑:程序博客网 时间:2024/06/05 22:50

Discription:

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.
Notes:
  • You must use only standard operations of a stack -- which means only push to toppeek/pop from topsize, and is 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).

Solution:

class MyQueue {private:stack<int> stack1;stack<int> stack2;public:/** Initialize your data structure here. */MyQueue() {}/** Push element x to the back of queue. */void push(int x) {stack1.push(x);}/** Removes the element from in front of queue and returns that element. */int pop() {int result = peek();stack2.pop();return result;}/** Get the front element. */int peek() {if (stack2.empty()){while (!stack1.empty()){int temp = stack1.top();stack1.pop();stack2.push(temp);}}int result = stack2.top();return result;}/** Returns whether the queue is empty. */bool empty() {if (stack2.empty() && stack1.empty())  //return stack2.empty() && stack1.empty()return true;elsereturn false;}};/*** 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();* bool param_4 = obj.empty();*/

0 0