Implement Stack using Queues && Implement Queue using Stacks

来源:互联网 发布:上海行知教育 编辑:程序博客网 时间:2024/06/07 13:08

Implement Stack using Queues

class Stack {private:    queue<int> q;public:    // Push element x onto stack.    void push(int x) {        queue<int> t;        while (!q.empty()) {            t.push(q.front());            q.pop();        }        q.push(x);        while(!t.empty()) {            q.push(t.front());            t.pop();        }    }    // Removes the element on top of the stack.    void pop() {        q.pop();    }    // Get the top element.    int top() {        while (!q.empty()) return q.front();    }    // Return whether the stack is empty.    bool empty() {        return q.empty();    }};


Implement Queue using Stacks

class Queue {private:    stack<int> s;public:    // Push element x to the back of queue.    void push(int x) {        stack<int> t;        while (!s.empty()) {            t.push(s.top());            s.pop();        }        s.push(x);        while(!t.empty()) {            s.push(t.top());            t.pop();        }    }    // Removes the element from in front of queue.    void pop(void) {        s.pop();    }    // Get the front element.    int peek(void) {        if (!s.empty()) return s.top();    }    // Return whether the queue is empty.    bool empty(void) {        return s.empty();    }};


0 0
原创粉丝点击