64,685
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
const int StackSize=100;
typedef struct sqst//定义栈的结构体
{
int data[StackSize];
int top;
}SqStack;
void InitStack(SqStack *st)//栈的初始化
{
st->top=-1;
}
int Push(SqStack *st,int x)//进栈操作
{
if(st->top==StackSize-1)
return 0;
else
{
st->top++;
st->data[st->top]=x;
return 1;
}
}
int Pop(SqStack *st,int &x)//出栈操作
{
if(st->top==-1)
return 0;
else
{
x=st->data[st->top];
st->top--;
return 1;
}
}
int GetTop(SqStack *st,int &x)//取栈顶元素
{
if(st->top==-1)
return 0;
else
{
x=st->data[st->top];
cout <<x <<endl;
return 1;
}
}
int StackEmpty(SqStack *st)//判断栈是否为空
{
if(st->top==-1)
return 1;
else
return 0;
}
int main()
{
SqStack s; //因为SqStack *s是定义了一个没有初始化的指针
InitStack(&s);
int a[]={1,2,3,4,5,6,7,8,9};
int i;
cout <<"判断栈是否为空,是则返回1否则为0" <<endl;
StackEmpty(&s);
cout <<"元素进栈" <<endl;
for(i=0;i <9;i++)
{
Push(&s,a[i]);
}
cout <<"取栈顶元素" <<endl;
for(i=0;i <9;i++)
{
GetTop(&s,a[i]);
}
cout <<"元素出栈" <<endl;
for(i=0;i <9;i++)
{
Pop(&s,a[i]);
}
return 0;
}
SqStack* s=new SqStack;