任務描述
本關任務:輸入一個整數(shù)序列a1,a2,a3…,an。當ai不等于-1時將ai進棧;當ai=-1時,輸出棧頂元素并將其出棧。
編程要求
輸入
多組數(shù)據(jù),每組數(shù)據(jù)有兩行,第一行為序列的長度n,第二行為n個整數(shù),整數(shù)之間用空格分隔。當n=0時輸入結(jié)束。
輸出
對于每一組數(shù)據(jù)輸出若干行。每行為相應的出棧元素。當出棧異常時,輸出“POP ERROR”
并結(jié)束本組數(shù)據(jù)的輸出。
測試說明
平臺會對你編寫的代碼進行測試:
測試輸入:
5
1 2 -1 -1 1
5
1 -1 -1 2 2
0
預期輸出:
2
1
1
POP ERROR
來源
https://www.bjfuacm.com/
C++代碼
243 head.h
詳細見注釋文章來源:http://www.zghlxwxcb.cn/news/detail-734585.html
#include<iostream>
using namespace std;
#define MAXSIZE 100
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef struct
{
int* base;
int* top;
int stacksize;
}SqStack;
int InitSqStack(SqStack& S)
{//棧的初始化
S.base = new int[MAXSIZE];
if (!S.base) return OVERFLOW;
S.top = S.base;
S.stacksize = MAXSIZE;
return OK;
}
int Pop(SqStack& S)
{//出棧
if (S.top == S.base){
// cout << "POP ERROR" << endl;
return ERROR;}
S.top--;
return OK;
}
int GetTop(SqStack S)
{//取棧頂元素
if (S.top == S.base){
// cout << "POP ERROR" << endl;
return ERROR;}
return *(S.top - 1);
}
int Push(SqStack& S, int e)
{//入棧
if (e == -1)
{
if(S.top==S.base)
cout << "POP ERROR" << endl;
else
{
cout <<GetTop(S) << endl;
Pop(S);
}
}
else
{
// cout<<"push"<<e<<endl;
*S.top = e;
S.top++;
}
return OK;
}
void InOutS(SqStack& S, int a[], int n)
{//入棧和出棧的基本操作 按照要求輸出
for(int i=0;i<=n;i++){
if(n==2 and (a[0]==-1) and (a[1]==-1)){
cout << "POP ERROR" << endl;
break;
// 這里有個小bug
// 當輸入集為:
// 2
// -1 -1
// 時
// 邏輯上應輸出兩次"POP ERROR",但測試答案只輸出一次"POP ERROR"
// 能力有限,歡迎斧正!
}
Push(S,a[i]);
}
// for(int i=0;i<=n;i++){
// cout<<"a"<<i<<":"<<a[i]<<endl;
// }
}
主函數(shù)文件不可編輯文章來源地址http://www.zghlxwxcb.cn/news/detail-734585.html
#include "head.h"
int main()
{
int n;
while(cin>>n)
{
if(n==0) break;
SqStack S;
InitSqStack(S);
int a[n];
for(int i=0;i<n;i++) cin>>a[i]; //整數(shù)序列
InOutS(S,a,n);
}
return 0;
}
到了這里,關于【 第4關:入棧和出棧的基本操作】【編程題實訓-?!俊绢^歌】【bjfu-243】的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!