您的位置:首页 > 理论基础 > 数据结构算法

数据结构之链式栈的构建

2016-02-02 12:03 573 查看
#include<iostream>
#include<cstdio>
#include<stdlib.h>
#include<malloc.h>
#include<math.h>
using namespace std;
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE  -1
#define STACK_INIT_SIZE 100
#define STACKINCREMENT  10
typedef int  Status;
typedef int Elemtype;
typedef struct{
Elemtype *base;
Elemtype *top;
int stacksize;//表示的是栈的空间大小与入栈出栈时候的操作无关
}Sqstack;
Status create(Sqstack &S);
Status destroy(Sqstack &S);
Status push(Sqstack &S);
Status pop(Sqstack &S,Elemtype &e);
int main()
{
Sqstack stack;//对结构体进行实例化
Elemtype r;
r=create(stack);
Elemtype i,e;
for(i=1;i<=5;i++)
{
r=push(stack);
}
while(stack.base!=stack.top)
{
r=pop(stack,e);

printf("%d",e);

}

return 0;
}

Status create(Sqstack &S)
{
S.base=S.top=(Elemtype*)malloc(STACK_INIT_SIZE*sizeof(Elemtype) );
if(S.base==NULL)
{
printf("内存分配失败,系统退出");
system("pause");
exit(OVERFLOW);
}
S.stacksize=STACK_INIT_SIZE;
return OK;
}
Status push(Sqstack &S)
{
Elemtype e;
if(S.top-S.base>=S.stacksize)
{
S.base=(Elemtype*)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(Elemtype) );
S.top=S.base+S.stacksize;
S.stacksize=S.stacksize+STACKINCREMENT;
}
printf("请输入你要增加的数字\n");
scanf("%d",&e);
*S.top++=e;
return OK;
}
Status destroy(Sqstack &S)
{
S.top=NULL;
free(S.base);
S.base=NULL;
S.stacksize=0;
return OK;
}
Status pop(Sqstack &S,Elemtype &e)
{
if(S.base==S.top){return ERROR;}
S.top--;
e=*S.top;//返回的e是删除之后的栈顶元素的值;
return OK;//栈顶指针不指向任何元素,因此取值的时候应该先-1在赋值;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: