您的位置:首页 > 其它

顺序栈实现

2017-06-11 23:43 176 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: