栈的基本概念
栈:就是线性表(线性结构)
与顺序表和单链表的区别:限制了插入和删除的位置
栈的特点:先进后出,指定在栈顶处进行操作
栈的实现(C语言)
- 栈的结构声明
typedef char ElemType;
typedef struct Stack
{
ElemType *stack_low; //存放数据的空间指针
int top; //栈顶指针
int size; //栈的大小
}Stack;
- 栈的函数声明
一般栈也就是初始化、入栈、出栈、取栈顶、判空、销毁这些方法
void InitStack(Stack *st, int init_size);
bool Empty(Stack *st);
bool Push(Stack *st, ElemType value);
bool Pop(Stack *st);
bool Top(Stack *st, ElemType *reval);
void DestroyStack(Stack *st);
- 栈的函数实现
#include "stack.h"
#include <string.h>
#include<stdio.h>
#include <stdlib.h>
#include<ctype.h>
static bool Full(Stack *st) //暂时性的判满函数
{
return st->top == st->size;
}
static bool AppendSpace(Stack *st) //申请拓展空间
{
ElemType *new_space = (ElemType*)malloc(sizeof(ElemType) * st->size * 2);
if(new_space == NULL) return false;
for(int i = 0; i < st->size; ++i)
{
new_space[i] = st->stack_low[i];
}
free(st->stack_low);
st->stack_low = new_space;
st->size *= 2;
return true;
}
void InitStack(Stack *st, int init_size) //初始化
{
if(st == NULL) exit(0);
init_size = init_size > 0 ? init_size : 10;
st->stack_low = (ElemType*)malloc(sizeof(ElemType) * init_size);
if(st->stack_low == NULL) exit(0);
st->top = 0;
st->size = init_size;
}
bool Empty(Stack *st) //判空
{
if(st == NULL) exit(0);
return st->top == 0;
}
bool Push(Stack *st, ElemType value) //入栈
{
if(st == NULL) exit(0);
if(Full(st))
{
if(!AppendSpace(st))
{
return false;
}
}
st->stack_low[st->top++] = value;
return true;
}
bool Pop(Stack *st) //出栈
{
if(st == NULL) exit(0);
if(Empty(st)) return false;
st->top--;
return true;
}
bool Top(Stack *st, ElemType *reval) //取栈顶
{
if(st == NULL) exit(0);
if(Empty(st)) return false;
*reval = st->stack_low[st->top - 1];
return true;
}
void DestroyStack(Stack *st) //销毁
{
if(st == NULL) exit(0);
free(st->stack_low);
st->stack_low = NULL;
st->top = st->size = 0;
}
栈的应用
1、 中缀表达式转后缀表达式
2、函数的递归调用
……