C 数据结构:栈的线式存储
一、实现
#include<stdio.h>
#include<stdlib.h>
typedef struct stack
{
int top_;//用来判断栈 空/满 的标记
int length_;//栈的长度
char *dataSpace_;
}Stack;
void initStack(Stack *stack, int len);//初始化栈
void push(Stack *stack, char ch);//压栈
int isFull(Stack *stack);
char pop(Stack *stack);//出栈
int isEmpty(Stack *stack);
void destroyStack(Stack *stack);
int main()
{
Stack s;
initStack(&s, 4);
if (!isFull(&s)) push(&s, 'A');
if (!isFull(&s)) push(&s, 'G');
if (!isFull(&s)) push(&s, 'M');
if (!isFull(&s)) push(&s, 'Y');
if (!isFull(&s)) push(&s, 'L');
while (!isEmpty(&s))
printf("%2c", pop(&s));
puts("");
destroyStack(&s);
return 0;
}
void initStack(Stack *stack, int len)
{
stack->top_ = 0;
stack->length_ = len;
stack->dataSpace_ = (char*)malloc(sizeof(char)*stack->length_);
if (NULL == stack->dataSpace_)
exit(-1);
}
void push(Stack *stack, char ch) { stack->dataSpace_[stack->top_++] = ch; }
int isFull(Stack *stack) { return stack->length_ == stack->top_; }
char pop(Stack *stack) { return stack->dataSpace_[--stack->top_]; }
int isEmpty(Stack *stack) { return 0 == stack->top_; }
void destroyStack(Stack *stack)
{
free(stack->dataSpace_);
stack->dataSpace_ = NULL;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/07577dc0ae97501d9589ee2ea97951cf.jpeg)
二、过程演示
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/9da41649372714f941ca16469fd9fe20.gif)