C++的STL队列实现栈
生活随笔
收集整理的這篇文章主要介紹了
C++的STL队列实现栈
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
使用C++的隊(duì)列STL實(shí)現(xiàn)一個(gè)棧的數(shù)據(jù)結(jié)構(gòu)
實(shí)現(xiàn)以下四個(gè)函數(shù):
1.push(x) : 將元素x壓入棧中
2.pop() : 彈出(移除)棧頂元素
3.top() : 返回棧頂元素
4.empty() : 判斷棧是否是空
隊(duì)列的數(shù)據(jù)結(jié)構(gòu)為先入先出,棧的數(shù)據(jù)結(jié)構(gòu)為先入后出;
即隊(duì)列的元素順序與棧中元素的順序是相反的,所以只需要保證后面插入的元素是在前面的元素之前能夠被彈出即可。
轉(zhuǎn)換成棧之后的存儲(chǔ)形態(tài),彈出隊(duì)列頭部的元素即類似與彈出棧頂元素
這里插入元素時(shí)維護(hù)一個(gè)臨時(shí)隊(duì)列,即可將原先隊(duì)列中的元素順序做一個(gè)逆置調(diào)整。
實(shí)現(xiàn)算法如下(文末有測(cè)試代碼):
void push(int x) {queue<int> tmp_queue;tmp_queue.push(x);/*對(duì)所有原隊(duì)列的元素做順序調(diào)整*/while (!data.empty()){tmp_queue.push(data.front());data.pop();}/*將調(diào)整后的順序放入原隊(duì)列,此時(shí)該隊(duì)列元素順序已經(jīng)為棧存儲(chǔ)的元素順序*/while (!tmp_queue.empty()){data.push(tmp_queue.front());tmp_queue.pop();}
}
實(shí)現(xiàn)如下:
#include <iostream>
#include <algorithm>
#include <queue>using namespace std;
class My_stack {private:queue<int> data;public:void push(int x) {queue<int> tmp_queue;tmp_queue.push(x);while (!data.empty()){tmp_queue.push(data.front());data.pop();}while (!tmp_queue.empty()){data.push(tmp_queue.front());tmp_queue.pop();}}/*彈出元素,即彈出隊(duì)列頭部元素*/int pop() {int x = data.front();data.pop();return x;}/*此時(shí)隊(duì)列中的元素已經(jīng)和棧存儲(chǔ)的元素同步了,直接返回對(duì)頭元素*/int top() {return data.front();} bool empty(){return data.empty();}
};int main() {My_stack s;cout << "construct the stack " << endl;int tmp;for (int i = 0;i < 5; ++i) {cin >> tmp;s.push(tmp);}cout << "top " << s.top() << endl;cout << "pop " << s.pop() << endl;cout << "top " << s.top() << endl;s.push(10);cout << "top after push '10' " << s.top() << endl;return 0;
}
輸出如下:
construct the stack
1 3 4 5 2
top 2
pop 2
top 5
top after push '10' 10
總結(jié)
以上是生活随笔為你收集整理的C++的STL队列实现栈的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 性激素六项失调症状
- 下一篇: C++的STL栈实现队列