#include <iostream>
using namespace std;
#define MAXSIZE 5//栈的大小
typedef struct//栈结构
{
int data[MAXSIZE];
int top;
}stack;
stack* creat_stack()//建立一个空栈
{
stack* s=NULL;
if((s=(stack *)malloc(sizeof(stack)))==NULL)
{
free(s);
return NULL;
}
s->top=-1;
return s;
}
bool empty_stack(stack* s)//判断栈是否为空
{
if((s->top)==-1)
return true;
else
return false;
}
bool full_stack(stack* s)//判断栈是否满
{
if(s->top==(MAXSIZE-1))
return true;
else
return false;
}
void push_stack(stack* s,int x)//入栈
{
//栈满不能入栈
if(full_stack(s))
cout<<"full_stack!"<<endl;
//否则将x入栈
else
{
s->top++;
s->data[s->top]=x;
cout<<"push number is"<<s->data[s->top]<<endl;
}
}
int pop_stack(stack* s)//出栈
{
//栈空没有元素可出栈
if(empty_stack(s))
{
cout<<"empty_stack!"<<endl;
return -1;
}
//否则出栈
s->top--;
return s->data[s->top+1];
}
int main(void)
{
//建立栈
stack* s=creat_stack();
if(s)
cout<<"creat_stack is succeesd"<<endl;
else
cout<<"creat_stack is failed!"<<endl;
//出栈
pop_stack(s);//输出栈空
//入栈
for(int i=0;i<6;++i)
{
push_stack(s,i);//栈满则停止入栈
}
//将栈中所有元素出栈
while(!empty_stack(s))
{
int number=pop_stack(s);
cout<<number<<" ";
}
free(s);
return 0;
}
栈
最新推荐文章于 2022-04-22 23:43:58 发布