简单栈操作

题目描述

【问题描述】

假设给定的整数栈初始状态为空,栈的最大容量为100。从标准输入中输入一组栈操作,按操作顺序输出出栈元素序列。栈操作:1表示入栈操作,后跟一个整数(不为1、0和-1)为入栈元素;0表示出栈操作;-1表示操作结束。

【输入形式】

从标准输入读取一组栈操作,入栈的整数和表示栈操作的整数之间都以一个空格分隔。

【输出形式】

在一行上按照操作的顺序输出出栈元素序列,以一个空格分隔各元素,最后一个元素后也要有一个空格。如果栈状态为空时进行出栈操作,或栈满时进行入栈操作,则输出字符串“error”,并且字符串后也要有一空格。所有操作都执行完后,栈也有可能不为空。

【样例输入】

1 3 1 5 1 7 0 0 1 8 0 1 12 1 13 0 0 0 0 1 90 1 89 0 -1

【样例输出】

7 5 8 13 12 3 error 89 


解题思路

        模拟栈操作,每次进栈出栈时根据返回值判断是否可以出栈即栈不为空


源代码

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
#define MaxSize 1000
typedef int ElemType;

//栈定义
typedef struct {
	ElemType data[MaxSize];
	int top;	/*栈指针*/
} SqStack;
//初始化栈
void InitStack(SqStack *&s) {
	s = (SqStack *)malloc(sizeof(SqStack));
	s->top = -1;
}
//判断栈为空
int StackEmpty(SqStack *s) {
	return s->top == -1;
}
//进栈
int Push(SqStack *&s, ElemType e) {
	if (s->top == MaxSize - 1)    //栈满的情况
		return 0;
	s->top++;
	s->data[s->top] = e;
	return 1;
}
//出栈
int Pop(SqStack *&s, ElemType &e) {
	if (s->top == -1)		//栈为空的情况
		return 0;
	e = s->data[s->top];
	s->top--;
	return 1;
}
int GetTop(SqStack *s, ElemType &e) {
	if (s->top == -1) 		//栈为空的情况,即栈下溢出
		return 0;
	e = s->data[s->top];
	return 1;
}

int main() {
	SqStack *lq;
	InitStack(lq);
	int flag = 1, x;
	while (flag != -1) {
		cin >> flag;
		if (flag == 1) {
			cin >> x;
			if (!Push(lq, x))
				cout << "error"<<" ";
		}
		else if (flag == 0) {
			if (!Pop(lq, x))
				cout << "error" << " ";
			else
				cout << x << " ";
		}
	}
	system("pause");
	return 0;
}

总结

        用于理解栈

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

想我记得写信

您的鼓励是我创作最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值