1 .給出類類型如下:有兩個成員變量,分別是兩個stack容器,存放的元素類型是 int;stack的特點(diǎn)是:先進(jìn)后出;而隊(duì)列queue的特點(diǎn)是先進(jìn)先出;現(xiàn)在用兩個 stack容器來實(shí)現(xiàn)隊(duì)列:
實(shí)現(xiàn)代碼:
------------------------------------- ------------- queue.h --------------- #pragma once #include <iostream> #include <stdlib.h> #include <stack> using namespace std; class Queue { private: stack<int> s1; stack<int> s2; public: //入隊(duì) void Push(const int& val); //出隊(duì) void Pop(); //返回隊(duì)首元素 int& Front(); //返回隊(duì)尾元素 int& Back(); //判斷隊(duì)列是否為空 bool Empty(); //返回隊(duì)列大小 int Size(); }; ---------------------------------------- ------------- queue.cpp ---------------- #include "queue.h" //入隊(duì) void Queue::Push(const int& val) { //棧s1作隊(duì)列的隊(duì)尾,s2作為隊(duì)列的隊(duì)頭 s1.push(val); cout<<val<<" "; } //出隊(duì) void Queue::Pop() { while (!s1.empty()) { int val = s1.top(); s2.push(val); s1.pop(); } s2.pop(); } //返回隊(duì)首元素 int& Queue::Front() { while (!s1.empty()) { s2.push(s1.top()); s1.pop(); } int temp = s2.top(); while (!s2.empty()) { int var = s2.top(); s1.push(var); s2.pop(); } return temp; } //返回隊(duì)尾元素 int& Queue::Back() { return s1.top(); } //判斷隊(duì)列是否為空 bool Queue::Empty() { if (s1.empty()&&s2.empty()) { return true; } else return false; } //返回隊(duì)列大小 int Queue::Size() { return s1.size()+s2.size(); } -------------------------------------- --------------- test.cpp ------------- #include "queue.h" void test() { Queue q1; cout<<"入隊(duì)列操作:"<<endl; cout<<"插入的隊(duì)列元素分別是:"<<endl; q1.Push(1); q1.Push(2); q1.Push(3); q1.Push(4); q1.Push(5); q1.Push(6); cout<<"判斷隊(duì)列是否為空!"<<endl; if (q1.Empty()) { cout<<"empty."<<endl; } else { cout<<"not empty."<<endl; } cout<<"獲取隊(duì)頭元素:"<<endl; cout<<q1.Front()<<endl; cout<<"獲取隊(duì)尾元素:"<<endl; cout<<q1.Back()<<endl; cout<<"獲取隊(duì)列的大小操作:"<<endl; cout<<q1.Size()<<endl; printf("出隊(duì)列操作:\n"); q1.Pop(); } int main() { test(); system("pause"); return 0; }
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)建站jinyejixie.com,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。
分享題目:C++基礎(chǔ)學(xué)習(xí)之利用兩個棧實(shí)現(xiàn)一個隊(duì)列-創(chuàng)新互聯(lián)
文章分享:http://jinyejixie.com/article26/pspjg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站排名、手機(jī)網(wǎng)站建設(shè)、網(wǎng)站設(shè)計(jì)公司、虛擬主機(jī)、電子商務(wù)、關(guān)鍵詞優(yōu)化
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容