栈的定义
栈是一种特殊的线性表,是仅在表尾进行插入和删除操作的线性表。
又称为后进后出(Last In First Out)的线性表,简称 LIFO 结构。
结构体定义栈和栈中元素的数据类型
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 66 //栈容量
typedef struct
{
int elem;
}Elemtype;
typedef struct
{
Elemtype* data;
int top;
}SqStack;
基本操作函数的声明
void initstack(SqStack* S);//初始化
void destroystack(SqStack* S);//销毁栈
int isempty(SqStack* S);//判断栈是否为空
int stacklength(SqStack* S);//栈长
void clearstack(SqStack* S);//清空栈
void push(SqStack* S, Elemtype x);//入栈
void pop(SqStack* S, Elemtype &x);//出栈
初始化
将 top 设为 -1,给栈中元素分配空间,初始化完成,即为空栈。
void initstack(SqStack* S)//初始化
{
S->top = -1;
S->data = (Elemtype*)malloc(sizeof(Elemtype)*MAXSIZE);
if(S->data == NULL)
{
printf("初始化失败!!\n");
return;
}
printf("初始化成功!!\n");
return;
}
销毁栈
释放掉初始化所为栈元素分配的空间。
void destroystack(SqStack* S)//销毁栈
{
S->top = -1;
free(S->data);
printf("栈已销毁!!!\n");
return;
}
判断栈是否为空
判断栈是否为空只需判断 top 是否为 -1 即可,top == -1,则栈为空,反之,则不为空。
int isempty(SqStack* S)//判断栈是否为空
{
if(S->top == -1)
return 1;
else
return 0;
}
栈长
int stacklength(SqStack* S)//栈长
{
int len = S->top+1;
return len;
}
清空栈
若要清空栈,则将 top 设为 -1 ,即可视为空栈。
void clearstack(SqStack* S)//清空栈
{
S->top = -1;
printf("栈已清空!!!\n");
return;
}
入栈
入栈前要判断此时栈是否已满,若栈已满,则无法入栈,若未满,则将栈顶标志 top 往上移动一个位置,再进行元素赋值,即可完成入栈。
void push(SqStack* S, Elemtype x)//入栈
{
if(S->top == MAXSIZE-1)
{
printf("栈已满!!\n");
return;
}
S->data[++S->top] = x;
printf("入栈成功!!!\n");
return;
}
出栈
出栈前需要判断栈是否为空,若为空,则无法进行出栈操作,若不为空,则将栈顶元素取出,栈顶标志 top 向下移动一个位置,即可完成出栈。
void pop(SqStack* S, Elemtype &x)//出栈
{
if(S->top == -1)
{
printf("栈为空!!\n");
return;
}
x = S->data[S->top--];
printf("出栈成功!!!\n");
return;
}
主函数
自行调用函数进行操作即可。
int main(void)
{
SqStack* S = (SqStack*)malloc(sizeof(SqStack));
initstack(S);
Elemtype x, y;
x.elem = 666;
push(S, x);//x入栈
pop(S, y);// y接收出栈的元素
//clearstack(S);
printf("%d\n", y.elem);
//destroystack(S);
int len = stacklength(S);
printf("%d\n", len);
if(isempty(S))
printf("栈为空!!");
else
printf("栈不为空!!");
return 0;
}