数据结构实验
问题描述:
假设以键盘输入的方式输入一个正整数序列:比如x1, x2, x3,…,xn,要求算法实现:当ai≠0时,将ai进栈;当ai=0时,栈顶元素出栈。最后将栈内留下的元素输出。用栈结构存储所输入的整数序列,并且要求算法的健壮性及能够应对异常情况(如果是顺序要判断栈满栈空,如果是链式栈要判断栈空等)并给出相应的提示系统信息。
试编程实现该程序。
① 输入的形式和输入值的范围:需要用户以键盘输入的方式输入一个正整数序列
② 输出的形式:通过运行程序后将最后的正整数序列输出。
③ 程序所能达到的功能:通过对栈的使用完成对正整数序列输出
④ 测试数据:13个元素 1203405607809
输出为:13579
代码:
main.cpp
#include <iostream>
#include "sqstack.h"
using namespace std;
int main()
{
SqStack *l;
InitStack(l);
Locate(l);
}
sqstack.h
#ifndef SQSTACK_H_INCLUDED
#define SQSTACK_H_INCLUDED
#define MaxSize 100
typedef int ElemType;
typedef struct
{
ElemType data[MaxSize];
int top; //栈指针
} SqStack; //顺序栈类型定义
void InitStack(SqStack *&s); //初始化栈
bool Push(SqStack *&s,ElemType e); //入栈
bool Pop(SqStack *&s,ElemType &e); //出栈
void DispStack(SqStack *s); //输出栈
void Locate(SqStack *&l);
#endif // SQSTACK_H_INCLUDED
sqstack.cpp
#include <stdio.h>
#include <malloc.h>
#include "sqstack.h"
void InitStack(SqStack *&s)
{
s=(SqStack *)malloc(sizeof(SqStack));
s->top=-1;
}
bool Push(SqStack *&s,ElemType e)
{
if (s->top==MaxSize-1) //栈满的情况
return false;
s->top++;
s->data[s->top]=e;
return true;
}
bool Pop(SqStack *&s,ElemType &e)
{
if (s->top==-1) //栈为空的情况
{
return false;
}
e=s->data[s->top];
s->top--;
return true;
}
void DispStack(SqStack *s) //倒序输出顺序栈
{
int i=s->top;
int j=0;
for (j;j<=i;j++)
printf("%d ",s->data[j]);
printf("\n");
}
void Locate(SqStack *&l)
{
l->top=-1;
printf("input:");
int y;
int s=0;
int x[110];
int i=0;
char a;
while ((a=getchar())!='\n') //将输入的数字存入数组
{
x[s]=a-'0';
s++;
}
if (s==0)
{
printf("stack is null!");
return;
}
else if (s==100)
{
printf("stack is full!");
}
while (x[i]>=0) //将数组中的数字送入栈
{
if (x[i]==0)
{
Pop(l,y);
}
else
{
Push(l,x[i]);
}
i++;
if (i==s)
{
break;
}
}
printf("output:");
DispStack(l);
}