栈
栈(Stack):是限制在表的一端进行插入和删除操作的线性表。又称为后进先出LIFO (Last In First Out)或先进后出FILO (First In Last Out)线性表。
栈顶(Top):允许进行插入、删除操作的一端,又称为表尾。用栈顶指针(top)来指示栈顶元素。
栈底(Bottom):是固定端,又称为表头。
空栈:当表中没有元素时称为空栈。
一 栈的静态顺序存储
注:bottom指的位置始终是0,即不存有效值;top始终指向有效值。
1.1 栈的基本类型定义
#define MAX_STACK_SIZE 100 //栈向量大小
#typedef int ElemType;
typedef struct sqstack{
ElemType stack_array[MAX_STACK_SIZE];
int top;
int bottom;
}SqStack;
1.2 栈的初始化
SqStack Init_Stack(void)
{
SqStack S;
S.bottom = S.top = 0;
return S;
}
1.3 压栈
/*使数据元素e进栈成为新的栈顶*/
Status push(SqStack S, ElemType e)
{
if(S.top == MAX_STACK_SIZE-1)
return ERROR; //栈满,返回错误标志
S.top++;
S.stack_array[S.top] = e; //e成为新的栈顶
return OK; //压栈成功
}
1.4 弹栈
/*弹出栈顶元素*/
Status pop(SqStack S, ElemType *e)
{
if(S.top == 0)
return ERROR; //栈空,返回错误标志
*e = S.stack_array[S.top];
S.top--;
return OK;
}
二 栈的动态顺序存储
注:bottom始终指向有效值;top取有效值要先自减1。
2.1 栈的类型定义
#define STACK_SIZE 100 //栈初始向量大小
#define STACKINCREMENT 10 //存储空间分配增量
#typedef int ElemType;
typedef struct sqstack{
ElemType *bottom; //栈不存在时值为NULL
ElemType *top; //栈顶指针
int stacksize; //当前分配空间,以元素为单位
}SqStack;
2.2 栈的初始化
Status Init_Stack(void)
{
SqStack S;
S.bottom = (ElemType *)malloc(STACK_SIZE*sizeof(ElemType));
if(!S.bottom)
return ERROR;
S.top = S.bottom; //栈空时栈顶和栈底指针相同
S.stacksize = STACK_SIZE;
return OK;
}
2.3 压栈
Status push(SqStack S, ElemType e)
{
if(S.top-S.bottom >= S.stacksize-1)
{
S.bottom = (ElemType *)realloc((STACKINCREMENT + STACK_SIZE)
*sizeof(ElemType)); //栈满,追加存储空间
if(!S.bottom)
return ERROR;
S.top = S.bottom + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top = e;
S.top++; //栈顶指针加1,e成为新的栈顶
return OK;
}
2.4 弹栈
Status pop(SqStack S, ElemType *e)
{
if(S.top == S.bottom)
return ERROR; //栈空,返回失败标志
S.top--;
e = *S.top;
return OK;
}
三 栈的链式存储
注:top->next才是栈顶元素。
typedef struct stacknode{
ElemType data;
struct Stack_Node *next;
}Stack_Node;
3.1 初始化
Stack_Node *Init_Link_Stack(void)
{
Stack_Node *top;
top = (Stack_Node *)malloc(sizeof(Stack_Node));
top->next = NULL;
return top;
}
3.2 压栈
Status push(Stack_Node *top, ElemType e)
{
Stack_Node *p;
p = (Stack_Node *)malloc(sizeof(Stack_Node));
if(!p)
return ERROR; //申请新结点失败,返回错误标志
p->data = e;
p->next = top->next;
top->next = p; //钩链
return OK;
}
3.3 弹栈
Status pop(Stack_Node *top, ElemType *e)
{
Stack_Node *p;
ElemType e;
if(top->next == NULL)
return ERROR; //栈空,返回错误标志
p = top->next;
e = p->data; //取栈顶元素
top->next = p->next; //修改栈顶指针
free(p);
return OK;
}
四 栈的应用
4.1 数制转换
/*将十进制整数n转换为d进制数*/
void conversion(int n, int d)
{
SqStack S;
int k, *e;
S = Init_Stack(); //用栈静态存储方式
while(n>0)
{
k = n%d; //求出所有的余数,进栈
push(S, k);
n = n/d;
}
while(S.top != 0) //栈不空时出栈,输出
{
pop(S, e);
printf("%1d", *e); //输出字符串格式
}
}
4.2 栈与递归调用的实现
为保证递归调用正确执行,系统设立一个“递归工作栈”,作为整个递归调用过程期间使用的数据存储区。每一层递归包含的信息如:参数、局部变量、上一层的返回地址构成一个“工作记录”。每进入一层递归,就产生一个新的工作记录压人栈顶;每退出一层递归,就从栈顶弹出一个工作记录。