栈的顺序存储
算法介绍
感觉顺序存储没什么难的… 感觉难的都在 栈的应用上, 或者来几道 ACM 的题
简单写三了个算法创建
压栈
出栈以后的有时间再补充
第一次代码实现——–2016年-9月-20号 ———–
一开始是想按照严太太书上的写, 但是写着写着感觉不对劲, 感觉心累,
为什么在 struct 里面定义那么多指针类型干嘛, 后面的代码虽然简洁, 非常实用, 但是感觉 对我不适合,
于是学习了 <<大话数据结构>> 这本书里面的.感觉也很棒!!!!
这次没有加注释...会补上的......
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define true 1
#define false 0
#define STACKSIZE 4
#define STACKINCREMENT 2
typedef int ElemType;
typedef int Position;
typedef int Status;
typedef struct Node{
ElemType *pBase;
Position top;
int stackSize;
} Node, *Stack;
Status initStack(Stack S);
Status push(Stack S, ElemType e);
Status pop(Stack S, ElemType *e);
int main(){
int i;
ElemType e;
Stack S = (Stack)malloc(sizeof(Node));
if(S == NULL){
printf("Memory allocation failed, program termination!!\n");
exit(-1);
}
initStack(S);
//压栈
push(S, 0);
push(S, 1);
push(S, 2);
push(S, 3);
push(S, 4);
//出栈
pop(S, &e);
return 0;
}
Status initStack(Stack S){
S->pBase = (ElemType*)malloc(sizeof(ElemType)*STACKSIZE);
if(S->pBase == NULL){
printf("Memory allocation failed, program termination!!\n");
exit(-1);
}
S->top = -1;
S->stackSize = STACKSIZE;
return true;
}
Status push(Stack S, ElemType e){
// if(S->top >= S->stackSize - 1){
// printf("栈已满, 压栈失败!!!\n");
// return false;
// }
if(S->top >= S->stackSize -1){
S->pBase = (ElemType*)realloc(S->pBase, sizeof(ElemType)*(STACKSIZE+STACKINCREMENT));
if(S->pBase == NULL){
printf("Memory allocation failed, program termination!!\n");
exit(-1);
}
S->stackSize += STACKINCREMENT;
}
printf("S->top 的值是: %d", S->top);
S->pBase[(++S->top)] = e;
printf("压栈成功\n");
return true;
}
Status pop(Stack S, ElemType *e){
if(S->top <= -1){
printf("栈已空, 出栈失败!!!\n");
return false;
}
*e = S->pBase[(S->top)--];
printf("出栈成功: %d\n", *e);
printf("S->top 的值是: %d", S->top);
return true;
}
仅供参考 ,有错误望指出.
有大神路过请指点一下。 菜鸟求飞 !!!
有什么疑问 也可以在 下边 提问 ! (有点托大了)或者发邮件
E-Mail:[email protected]