LeetCode 232. Implement Queue using Stacks

来源:互联网 发布:男孩被父砍29刀 知乎 编辑:程序博客网 时间:2024/05/20 03:37

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.


Use two stacks to implement it.


#include <stack>#include <iostream>using namespace std;// implement queue using stacks.// we need to use two stacks, one for the pusing elements in, one for poping elements out.// suppose we use stack_1 for pushing elements, stack_2 for poping elements.class Queue {    private:        stack<int> stack_1;        stack<int> stack_2;    public:        void push(int x) {            stack_1.push(x);        }        void pop(void) {            if(stack_2.empty()) {                while(!stack_1.empty()) {                    int tmp = stack_1.top();                    stack_1.pop();                    stack_2.push(tmp);                }            }            stack_2.pop();        }        int peek(void) {            if(stack_2.empty()) {                while(!stack_1.empty()) {                    int tmp = stack_1.top();                    stack_1.pop();                    stack_2.push(tmp);                }            }            return stack_2.top();        }        bool empty(void) {            return stack_1.empty() && stack_2.empty();        }};int main(void) {    Queue t1;    t1.push(0);    cout << t1.peek() << endl;    cout << t1.empty() << endl;}                                                                                                                                                                        1,1           Top


0 0