栈的概念:
栈,仅限定为表尾进行插入或删除操作的线性表。
栈顶——top
栈底——bottom
特性:
后进先出(last in first out)
用C/C++实现栈的算法:
#include <malloc.h>
#define STACK_INIT_SIZE 100
#define STACK_INCREMENT 10
#ifndef SElemType
typedef int SElemType;
#endif
typedef struct{
SElemType *base;//栈底
SElemType *top;//栈顶
int stacksize;//栈的当前可使用的最大容量
}SqStack;
//构造一个空栈
int InitStack(SqStack &stack);
//销毁栈
int DestroyStack(SqStack &stack);
int GetTop(SqStack &stack,SElemType &data);
int Push(SqStack &stack,SElemType data);
int Pop(SqStack &stack,SElemType &data);
//插入data为栈顶元素
int Push(SqStack &stack,SElemType data);
int InitStack(SqStack &stack)
{
stack.base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if(!stack.base)return 0;
stack.top = stack.base;
stack.stacksize = STACK_INIT_SIZE;
return 1;
}
int DestroyStack(SqStack &stack)
{
if(stack.top == stack.base)return 1;
free(stack.base);
stack.base = stack.top = NULL;
}
int GetTop(SqStack &stack,SElemType &data)
{
if(stack.top == stack.base)return 0;
data = *(stack.top - 1);
return 1;
}
int Push(SqStack &stack,SElemType data)
{
if((stack.top-stack.base) >= stack.stacksize)//满栈,添加存储空间
{
/*realloc 内存扩大,并拷贝源内存数据*/
stack.base = (SElemType *)realloc(stack.base,(stack.stacksize+STACK_INCREMENT)*sizeof(SElemType));
if(!stack.base)return 0;
stack.top = stack.base + stack.stacksize;
stack.stacksize += STACK_INCREMENT;
}
*stack.top++ = data;
return 1;
}
int Pop(SqStack &stack,SElemType &data)
{
if(stack.top == stack.base)return 0;
data = *(--stack.top);
return 1;
}
int IsEmpty(SqStack &stack)
{
if(stack.top != stack.base)return 0;
return 1;
}
栈的应用:
数值转换
输入任意一个非负10进制整数,打印输出其对应的8进制整数:
//数制转换——将10进制转成8进制
void ConversionToO()
{
SqStack stack;
int d;
InitStack(stack);
scanf("%d",&d);
while(d)
{
Push(stack,d%8);
d /= 8;
}
while(!IsEmpty(stack))
{
Pop(stack,d);
printf("%d",d);
}
printf("\r\n");
}