1 .給出類類型如下:有兩個成員變量,分別是兩個stack容器,存放的元素類型是 int;stack的特點是:先進后出;而隊列queue的特點是先進先出;現(xiàn)在用兩個 stack容器來實現(xiàn)隊列:

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