【 第4关:入栈和出栈的基本操作】【编程题实训-栈】【头歌】【bjfu-243】

任务描述

本关任务:输入一个整数序列a1,a2,a3…,an。当ai不等于-1时将ai进栈;当ai=-1时,输出栈顶元素并将其出栈。

编程要求

输入
多组数据,每组数据有两行,第一行为序列的长度n,第二行为n个整数,整数之间用空格分隔。当n=0时输入结束。

输出
对于每一组数据输出若干行。每行为相应的出栈元素。当出栈异常时,输出“POP ERROR”并结束本组数据的输出。

测试说明
平台会对你编写的代码进行测试:

测试输入:

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
详细见注释

#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;
//    }
}

主函数文件不可编辑

#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];  //整数序列
		InOutS(S,a,n);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Tommy_Nike/article/details/127581536
今日推荐