C++的STL栈实现队列

使用内部存储结构为栈的方法实现一个队列,要求实现该队列的如下方法:
1.push(x) : 将元素x压入队列中
2.pop() : 弹出(移除)队列头部元素
3.peek() : 返回队列头部元素(即为front)
4.empty() : 判断队列是否是空

栈的数据结构为先入后出,队列的数据结构为先入先出
使用栈来实现队列,同样想要让两者弹出的数据保持一直,内部的数据存储顺序是相反的;

可行的办法是维护一个临时栈,用来调换真正存储数据的栈中元素的存储顺序

C++的STL栈实现队列_第1张图片

实现如下:

void push(int x) {
    stack<int> tmp_data;
	/*维护一个临时栈,用来进行数据顺序的调换*/
    while (!data.empty())
    {
        tmp_data.push(data.top());
        data.pop();
    }
    tmp_data.push(x);
    while (!tmp_data.empty())
    {
        data.push(tmp_data.top());
        tmp_data.pop();
    }
}

测试代码如下:

#include 
#include 
#include 

using namespace std;

class My_queue {
    private:
    stack<int> data;
    public:
    void push(int x) {
        stack<int> tmp_data;
        while (!data.empty())
        {
            tmp_data.push(data.top());
            data.pop();
        }
        tmp_data.push(x);
        while (!tmp_data.empty())
        {
            data.push(tmp_data.top());
            tmp_data.pop();
        }
    }

    int pop() {
        int x = data.top();
        data.pop();
        return x;
    }
    
    /*返回队列头部元素*/
    int peek() {
        return data.top();
    }

    bool empty() {
        return data.empty();
    }
};

int main() {
    My_queue q;
    cout << "construct the queue " << endl;
    int tmp;
    for (int i = 0;i < 5; ++i){
        cin >> tmp;
        q.push(tmp);
    }

    cout << "pop " << q.pop() << endl;
    cout << "peek " << q.peek() << endl;
    q.push(10);
    cout << "peek push '10' " << q.peek() << endl;

    return 0;
}

输出如下:

construct the queue 
1 2 3 4 5
pop 5
peek 4
peek push '10' 10

你可能感兴趣的:(#,编程语言:C++,#,数据结构:线性表,编程语言)