剑指offer之两个队列实现栈的问题
1 問題
兩個隊列實現棧的插入和獲取頭部元素的功能
?
?
?
?
?
?
?
2 分析
1)獲取頭部元素的功能分析:
我們有2個隊列,我們知道隊列的特點的先進先出,而棧的特點是先進后出,比如我們有數據1,2,3,4,我們分別依次壓入隊列1,隊列2目前是空,我們需要有棧的效果,加上隊列2也是先進先出的特點,意味著我們隊列2里面的數據依次是4,3,2,1入隊列2,現在問題轉成了我們怎么操作隊列1里面的數據讓它依次彈出4,3,2,1入隊列2
接下來我們分析怎么操作隊列1里面的數據讓它依次彈出4,3,2,1入隊列2
我們知道隊列1數據進去的時候是1,2,3,4.我們需要得到4,我們可front()得到進入隊列的第一個元素,然后push到隊列1,然后執行pop()函數,那么隊列1就變成了2,3,4,1, 同理我們也這樣操作,知道元素4在隊列的最頭部,隊列1也就變成了3,2,1,4,我們把4彈出來壓入到隊列2里面去,然后隊列1的數據是3,2,1,我們依然按照上面的方法,把3彈出來壓入隊列2,最后隊列2就入隊列的元素依次是4,3,2,1 再把隊列2彈出頭部元素,就是我們棧獲取頭部元素的效果。
?
2)插入元素的功能分析:
如果隊列2不為空的情況下,我們需要先把隊列2里面的元素一一彈出來放到(push)隊列1里面去,確保隊列2是空的之后,然后再把新的元素push到隊列的1的尾巴
如果隊列2為空的情況下,我們可以直接把新的元素push到隊列1里面去就行。
?
?
?
?
3 代碼實現
#include <iostream> #include <queue>using namespace std;class student { public:student(){}~student(){}student(std::string name, std::string age, std::string sex) {this->name = name;this->age = age;this->sex = sex;}void toString(){std::cout << "name is "<< name << " age is "<< age << " sex is "<< sex << std::endl;} private:std::string name;std::string age;std::string sex; };template <typename T> class Test { public:Test(){}~Test(){}Test(const T& t);//往隊列里面添加元素void add(const T& t);//往隊列里面刪除元素T top(); private:std::queue<T> queue1;std::queue<T> queue2; };template <typename T> void Test<T>::add(const T& t) {if (!queue2.empty()){T& top = queue2.front();queue1.push(top);queue2.pop();}queue1.push(t); }template <typename T> T Test<T>::top() {if (queue2.empty()){while (!queue1.empty()){int size = queue1.size();for (int i = 1; i < size; ++i){T& top = queue1.front();queue1.push(top);queue1.pop();}T& value = queue1.front();queue2.push(value);queue1.pop();}}T top = queue2.front();queue2.pop();return top; } int main() {student std1("chenyu", "27", "man");student std2("chencaifeng", "27", "woman");student std3("chenzixuan", "3", "woman");student std4("chenzixi", "2", "woman");student std5("chenxuan", "21", "man");Test<student> stack;stack.add(std1);stack.add(std2);stack.add(std3);stack.add(std4);student top1 = stack.top();top1.toString();student top2 = stack.top();top2.toString(); student top3 = stack.top();top3.toString(); std::cout << "--------------------" << std::endl; stack.add(std5);student top4 = stack.top();top4.toString(); student top5 = stack.top();top5.toString(); return 0; }?
?
?
?
?
4 運行結果
name is chenzixi age is 2 sex is woman name is chenzixuan age is 3 sex is woman name is chencaifeng age is 27 sex is woman -------------------- name is chenxuan age is 21 sex is man name is chenyu age is 27 sex is man如果我分析的有點問題或者哪里沒有考慮到,歡迎大家指出來。?
?
最后附加:
我的微信:
打賞博主 非常感謝:
?
總結
以上是生活随笔為你收集整理的剑指offer之两个队列实现栈的问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 剑指offer之和为s的数组
- 下一篇: 剑指offer之二叉搜索树的第K个节点