#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
//----------顺序栈的实现-------------
#define STACK_INIT_SIZE 100
#define STACKINCREAMENT 10
#define OVERFLOW -2
#define OK 1
#define ERROR 0
typedef int ElemType;
typedef struct{
ElemType *base;
ElemType *top;
int stacksize;
}SqStack;
int InitStack(SqStack &s){
s.base=(ElemType * )malloc(STACK_INIT_SIZE * sizeof(ElemType));
if(!s.base)exit(OVERFLOW);
s.top=s.base;
s.stacksize=STACK_INIT_SIZE;
return OK;
}
bool Empty(SqStack s){
return s.base == s.top;
}
int GetTop(SqStack s,ElemType &e){
if(Empty(s))return ERROR;
e=*(s.top-1);
return OK;
}
int Push(SqStack &s,ElemType &e){
if(s.top-s.base >= s.stacksize){
s.base = (ElemType * )realloc(s.base,((s.stacksize + STACKINCREAMENT) * sizeof(ElemType)));
if(!s.base)return ERROR;
s.top = s.base+s.stacksize;
s.stacksize += STACKINCREAMENT;
}
*s.top++ = e;
return OK;
}
int Pop(SqStack &s,ElemType &e){
if(Empty(s))return ERROR;
e = *(--s.top);
return OK;
}
void print(SqStack s){
int e;
while(!Empty(s)){
Pop(s,e);
cout<< e <<" ";
}
cout<<endl;
}
int main()
{
int arr[]={1,2,3,4,5,6,7,8,9};
SqStack s;InitStack(s);
for(int i=0;i<9;++i)Push(s,arr[i]);
print(s);
return 0;
}
顺序栈实现
最新推荐文章于 2024-08-29 20:49:35 发布