建立一个顺序栈。实现基本操作
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
#define MaxSize 100 //定义栈的大小
typedef int type;
typedef struct stack
{
type data[MaxSize];//栈中元素数组
int top; //栈顶元素位置
}SeqStack,*SStack;
//置栈空(初始化顺序堆栈)
void InitSeqStack(SStack s)
{
s->top=-1;
}
//判断堆栈是否为空
bool EmptyStack(SStack s)
{
if(-1==s->top)
return true;
else
return false;
}
//判断栈满
bool FullStack(SStack s)
{
if(s->top==MaxSize-1)
return true;
else
return false;
}
//进栈
void PushStack(SStack s, type data)
{
if(FullStack(s))
{
cout<<"栈满"<<endl;
return ;
}
else
{
s->data[++s->top]=data;
}
}
//出栈
type PopStack(SStack s)
{
if(EmptyStack(s))
{
cout<<"栈空"<<endl;
return NULL;
}
else
{
return s->data[s->top--];
}
}
//打印顺序栈
void PrintSeqStack(SStack s)
{
if(EmptyStack(s))
{
printf("栈为空!");
exit(EXIT_FAILURE);
}
while(-1!=s->top)
{
printf("%3d",s->data[s->top--]);
}
printf("\n");
}
int main()
{
type a[6]={10,11,12,13,14,15};
SStack s=(SStack)malloc(sizeof(SeqStack));
InitSeqStack(s);
for(int i=0;i<6;i++)
PushStack(s,a[i]);
PrintSeqStack(s);
return 0;
}
