数据结构学习-Unit3栈与队列-栈
栈是一种重要的线性结构,具有后进先出的特性。元素只能从栈顶端压入,也只能从栈顶端弹出。
我们先来看栈的结构:
typedef struct stac
{
int *top;
int *bottom;
int stacksize;
}Stack;
top即栈顶,位置比最上方元素位置高一位。
bottom即栈底,位置指向最下方元素。
当栈为空时,有top==bottom
栈有以下几种常用操作:
void InitStack(Stack &S);//栈的初始化
void DestroyStack(Stack &S);//摧毁栈
void ClearStack(Stack &S);//清空栈
int StackEmpty(Stack S);//判断栈是否为空
int StackLength(Stack S);//求栈的长度
void GetTop(Stack S,int &e);//取得栈顶元素
void Push(Stack &S,int e);//压入元素
void Pop(Stack &S,int &e);//弹出元素
栈的初始化的实现:
void InitStack(Stack &S)//初始化栈
{
S.bottom=(int *)malloc(SIZE*sizeof(int));
if(S.bottom==NULL) exit(1);
S.top=S.bottom;
S.stacksize=SIZE;
}
压入元素:
void Push(Stack &S,int e)//压入
{
if(S.top-S.bottom>=SIZE)//栈满的情况
{
S.bottom=(int *)realloc(S.bottom,(ADD_SIZE+S.stacksize)*sizeof(int));
if(S.bottom==NULL) exit(1);
S.top=S.bottom+S.stacksize;
S.stacksize=S.stacksize+ADD_SIZE;
}
*S.top++=e;//top指向的位置的值改为e,然后top位置上升1位
}
弹出元素:
void Pop(Stack &S,int &e)//弹出
{
if(S.top==S.bottom)//栈为空
{
printf("Error");
return;
}
e=*--S.top;//top位置下降一位,指向栈中最上方元素,再把该元素的值赋给e
}
取得栈顶元素:
void GetTop(Stack S,int &e)//返回栈顶元素(不同于Pop()函数)
{
if(S.top==S.bottom)
{
printf("Error");
return ;
}
e=*(S.top-1);//注意对比Pop函数
}
摧毁栈:
void DestroyStack(Stack &S)//摧毁栈
{
free(S.bottom);
S.top=NULL;
S.bottom=NULL;
S.stacksize=0;
}
栈的清空
void ClearStack(Stack &S)//清空栈
{
S.top=S.bottom;//其余的元素不需要做处理,因为压入元素时会自动覆盖原数据
}
判断栈是否为空:
int StackEmpty(Stack S)//判断栈是否为空
{
if(S.top==S.bottom)
{
return 1;//1表示空
}
return 0;//0表示非空
}
栈的长度:
int StackLength(Stack S)
{
return (S.top-S.bottom);
}