习题3.3

设从键盘输人一整数的序列:a1,a2,a3,…,an,试编写算法实现:用栈结构存储输入的整数,当ai≠-1时,将ai进栈;当ai=-1时,输出栈顶整数并出栈。算法应对异常情况(入栈满等)给出相应的信息。

完整代码:

#include <iostream>
#include <string.h>
using namespace std;
typedef int Status;
typedef int TypeStack;

#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAX 100  //栈空间初始大小




//顺序栈
typedef struct SqStack 
{
	TypeStack* top;//栈顶指针
	TypeStack* base; //栈底指针
	int size;//当前栈空间的大小
}SqStack;


void readan(SqStack &S);

bool EmptyStack(SqStack S)
{

if(S.top==S.base)

return true ;

else return false ;

}

Status InitStack(SqStack &S)
{
    S.base=new TypeStack[MAX];
    if(!S.base) exit(OVERFLOW);
    S.top=S.base;
    S.size=MAX;
    return OK;
}

Status push(SqStack &S,TypeStack e)
{
    if(S.top-S.base==S.size)
    {
        cout<< "栈满!" << endl;
        return ERROR;
    }
    *S.top=e;
    *S.top++;
    return OK;

}

Status Pop(SqStack &S,TypeStack &e)
{
    if(S.top==S.base) 
    {
        cout<< "栈为空" << endl;
		return ERROR;
    }
    *--S.top;
    e=*S.top;
    return OK;
}

TypeStack GetTop(SqStack S)
{
    if(S.top!=S.base)
    return *(S.top-1);
}

Status PrintStack(SqStack S)
{
    TypeStack *x=S.base;
    while(x<S.top)
    {   
        cout<<*x<<" ";
        x++;

    }
    return OK;
}

Status somepush(SqStack &S)
{
    int num;
    int i=0;
    TypeStack n;
    cout << "输入元素个数n,初始化栈" << endl;
	cin >> num;
	cout << "请依次输入元素:" << endl;
    while(1)
    {
        cin>>n;
        push(S,n);
        i++;
        if(i==num) break;
    }
}
int main()
{   
SqStack S;
InitStack(S);
readan(S);
cout<<endl;
PrintStack(S);


return 0;
}

void readan(SqStack &S)
{
    int x=0,i=0;
    char ch;
    while(1)
    {
        cin>>x;
        ch=getchar();
        if(x!=-1) push(S,x);
        else {Pop(S,i);cout<<"读取到-1,栈顶元素"<<i<<"出栈"<<endl;}

        if(ch=='\n') break;

    }
 }

 

版权声明:
作者:maple
链接:http://haut.vip/?p=144
来源:欢迎来到计服社
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
海报
习题3.3
设从键盘输人一整数的序列:a1,a2,a3,…,an,试编写算法实现:用栈结构存储输入的整数,当ai≠-1时,将ai进栈;当ai=-1时,输出栈顶整数并出栈。算法应对异常情……
<<上一篇
下一篇>>