設(shè)計(jì)一個(gè)函數(shù)實(shí)現(xiàn)以下功能的函數(shù),并測(cè)試。
設(shè)從鍵盤(pán)輸入一整數(shù)的序列:a1,a2,a3,...,an,用棧結(jié)構(gòu)存儲(chǔ)輸入的整數(shù),當(dāng)ai不等于-1時(shí),將ai進(jìn)棧;當(dāng)ai=-1時(shí),輸出棧頂整數(shù)并出棧。注意要應(yīng)對(duì)異常情況(入棧滿(mǎn)等)給出相應(yīng)的信息。
輸出結(jié)果:?
?
?文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-745495.html
?主要算法:
//當(dāng)ai不為-1時(shí),將ai進(jìn)棧;當(dāng)ai=-1時(shí),輸出棧頂整數(shù)并出棧
void Yes_No(SqStack &S,int a) {
if (a == -1) {
int e{};
Pop(S,e);
cout <<e<<" ";
}
else {
Push(S,a);
}
}
完整代碼:?
#include<iostream>
using namespace std;
//定義順序棧
#define MAXSIZE 10
typedef struct
{
char* base;
char* top;
int stacksize;
}SqStack;
//初始化
int InitStack(SqStack& S)
{
S.base = new char[MAXSIZE];
if (!S.base)
return OVERFLOW;
S.top = S.base;
S.stacksize = MAXSIZE;
return 1;
}
//入棧
int Push(SqStack& S, int &e)
{
if (S.top - S.base == S.stacksize)
{
cout << "棧已滿(mǎn)!";
return 0;
}
*S.top++ = e;
return 1;
}
//出棧
int Pop(SqStack& S, int &e)
{
if (S.top == S.base)
{
cout << "棧為空!";
return 0;
}
e = *--S.top;
return 1;
}
//當(dāng)ai不為-1時(shí),將ai進(jìn)棧;當(dāng)ai=-1時(shí),輸出棧頂整數(shù)并出棧
void Yes_No(SqStack &S,int a) {
if (a == -1) {
int e{};
Pop(S,e);
cout <<e<<" ";
}
else {
Push(S,a);
}
}
int main()
{
SqStack S;
InitStack(S);
cout << "請(qǐng)輸入一整數(shù)序列(以*結(jié)尾):";
int a;
while(cin>>a)
{
Yes_No(S,a);
}
cout << endl;
cout << "棧中元素為:";
while (S.top!=S.base)
{
int e{};
Pop(S, e);
cout << e;
}
return 0;
}
?文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-745495.html
?
到了這里,關(guān)于設(shè)從鍵盤(pán)輸入一整數(shù)的序列:a1,a2,a3,...,an,用棧結(jié)構(gòu)存儲(chǔ)輸入的整數(shù),當(dāng)ai不等于-1時(shí),將ai進(jìn)棧;當(dāng)ai=-1時(shí),輸出棧頂整數(shù)并出?!緮?shù)據(jù)結(jié)構(gòu)】【?!康奈恼戮徒榻B完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!