#include<stdio.h>
#include<sys/malloc.h>
#include<stdlib.h>
#define ERROR 0
#define OK 1
#define STACK_INT_SIZE 5 /*存储空间初始分配量*/
#define STACKINCREMENT 5 /*存储空间分配增量*/
typedef int ElemType; /*定义元素类型*/
typedef struct{
ElemType *base;
ElemType top;
int stacksize; /*当前已经分配的存储空间*/
}SqStack;
int InitStack(SqStack *S); /*构造空栈*/
int push(SqStack *S,ElemType *e); /*入栈*/
int pop(SqStack S,ElemType *e); /*出栈*/
int CreateStack(SqStack *S); /*创建栈*/
void PrintStack(SqStack *S); /*出栈并输出栈中元素*/
int InitStack(SqStack *S){
S->base=(ElemType *)malloc(STACK_INT_SIZE*sizeof(ElemType));
if (!S->base) {
return ERROR;
}
S->top=-1;
S->stacksize=STACK_INT_SIZE;
return OK;
}
int Push(SqStack *S,ElemType e){
if(S->top==STACK_INT_SIZE-1){
S->base=(ElemType *)realloc(S->base, STACKINCREMENT*sizeof(ElemType));
S->stacksize=S->stacksize+STACKINCREMENT;
}
S->top++;
*(S->base+S->top)=e;
return 1;
}
int Pop(SqStack *S,ElemType *e){
if(S->top==-1) return 0;
else{
*e=*(S->base+S->top);
S->top--;
return 1;
}
}
int CreateStack(SqStack *S){
int e;
if(InitStack(S))
printf("Init Success!\n");
else{
printf("Init Fall!\n");
return ERROR;
}
printf("input data:(Terminated by inputing a character)\n");
while (scanf("%d",&e))
Push(S, e);
return OK;
}
void PrintStack(SqStack *S){
ElemType e;
while (Pop(S, &e)) {
printf("%3d",e);
}
}
int main() {
SqStack SS;
printf("\n1-createStack\n");
CreateStack(&SS);
printf("\n2-createStack\n");
PrintStack(&SS);
printf("\n");
return 0;
}
顺序栈基本操作(动态分配空间)
最新推荐文章于 2024-10-10 21:21:44 发布