且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[LeetCode]232.Implement Queue using Stacks

更新时间:2022-08-12 18:35:36

题目

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 top, peek/pop from top, size, 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).

思路

两个栈模拟队列

代码

/*---------------------------------------
*   日期:2015-08-01
*   作者:SJF0115
*   题目: 232.Implement Queue using Stacks
*   网址:https://leetcode.com/problems/implement-queue-using-stacks/
*   结果:AC
*   来源:LeetCode
*   博客:
-----------------------------------------*/
#include <iostream>
#include <vector>
#include <stack>
using namespace std;

class Queue {
public:
    // Push element x to the back of queue.
    void push(int x) {
        firStack.push(x);
    }

    // Removes the element from in front of queue.
    void pop(void) {
        if(!secStack.empty()){
            secStack.pop();
            return;
        }//if
        if(firStack.empty()){
            return;
        }//if
        while(!firStack.empty()){
            secStack.push(firStack.top());
            firStack.pop();
        }//while
        secStack.pop();
    }

    // Get the front element.
    int peek(void) {
        if(!secStack.empty()){
            return secStack.top();
        }//if
        //no pop or peek operations will be called on an empty queue
        if(firStack.empty()){
            return -1;
        }//if
        while(!firStack.empty()){
            secStack.push(firStack.top());
            firStack.pop();
        }//while
        return secStack.top();
    }

    // Return whether the queue is empty.
    bool empty(void) {
        return firStack.empty() && secStack.empty();
    }
private:
    stack<int> firStack;
    stack<int> secStack;
};

int main(){
    Queue q;
    for(int i = 0;i < 5;++i){
        q.push(i);
    }//for
    while(!q.empty()){
        cout<<q.peek()<<" ";
        q.pop();
    }//while
    q.push(8);
    cout<<q.peek()<<endl;
    q.pop();
    cout<<q.peek()<<endl;
    return 0;
}