栈的定义
栈是一种比较特殊的线性表,它的操作受限,其限制是仅允许在表的一端进行插入和删除运算, 这种限制造成栈最先进入的元素最晚出栈,也就是FILO(First In, Last Out)。 可以操作的一端被称为栈顶,另一端称之为栈底。向一个栈插入新元素称为压栈push(将新元素放在栈顶元素的上面,成为新的栈); 从一个栈删除元素称为出栈pop (将栈顶元素删除,使栈顶元素下面的元素成为新的栈顶元素)
栈的结构
- 使用静态数组来存放栈中元素,其中top元素记录栈顶的位置属性
typedef char Elemtype;
typedef struct{
Elemtype data[STACK_MAX_SIZE];
int top;
}SqStack;
栈的基本运算实现
- 栈的初始化
/*
初始化栈
*/
Status InitStack(SqStack *s)
{
s->top = -1;
return OK;
}
- 栈空判断
/*
栈空判断
*/
Status StackEmpty(SqStack s)
{
if (s.top == -1)
return TRUE;
else
return FALSE;
}
- 压栈
/*
压栈
*/
Status Push(SqStack *s, Elemtype e)
{
if (s->top >= STACK_MAX_SIZE - 1)
return OVERFLOW; //已达到最大的容量
s->top++;
s->data[s->top] = e;
return OK;
}
- 出栈
/*
出栈
*/
Status Pop(SqStack *s, Elemtype *e)
{
if (StackEmpty(*s))
return ERROR;
else{
*e = s->data[s->top];
s->top--;
return OK;
}
}
- 显示栈顶元素
/*
显示栈顶元素
*/
Status GetTop(SqStack s, Elemtype *e)
{
if (StackEmpty(s))
return ERROR;
else{
*e = s.data[s.top];
return OK;
}
}
- 得到栈中数据长度
/*
得到栈的长度
*/
Status GetLength(SqStack s)
{
return s.top + 1;
}
- 显示栈中数据内容
/*
显示栈中存放的数据
*/
Status DispStack(SqStack s)
{
int i;
if (StackEmpty(s)){
printf("空栈\n");
return ERROR;
}
else{
for (i = 0; i < GetLength(s); ++i){
printf("%c ", s.data[i]);
}
printf("\n");
return OK;
}
}
测试完整代码
#if 0
实现了顺序栈(采用的是静态数组的形式)
#endif
#include <stdio.h>
#include <stdlib.h>
#define STACK_MAX_SIZE 20
#define OK 1
#define ERROR 0
#define OVERFLOW -1
#define TRUE 1
#define FALSE 0
typedef int Status;
typedef char Elemtype;
typedef struct{
Elemtype data[STACK_MAX_SIZE];
int top;
}SqStack;
/*
初始化栈
*/
Status InitStack(SqStack *s)
{
s->top = -1;
return OK;
}
/*
栈空判断
*/
Status StackEmpty(SqStack s)
{
if (s.top == -1)
return TRUE;
else
return FALSE;
}
/*
压栈
*/
Status Push(SqStack *s, Elemtype e)
{
if (s->top >= STACK_MAX_SIZE - 1)
return OVERFLOW; //已达到最大的容量
s->top++;
s->data[s->top] = e;
return OK;
}
/*
出栈
*/
Status Pop(SqStack *s, Elemtype *e)
{
if (StackEmpty(*s))
return ERROR;
else{
*e = s->data[s->top];
s->top--;
return OK;
}
}
/*
显示栈顶元素
*/
Status GetTop(SqStack s, Elemtype *e)
{
if (StackEmpty(s))
return ERROR;
else{
*e = s.data[s.top];
return OK;
}
}
/*
得到栈的长度
*/
Status GetLength(SqStack s)
{
return s.top + 1;
}
/*
显示栈中存放的数据
*/
Status DispStack(SqStack s)
{
int i;
if (StackEmpty(s)){
printf("空栈\n");
return ERROR;
}
else{
for (i = 0; i < GetLength(s); ++i){
printf("%c ", s.data[i]);
}
printf("\n");
return OK;
}
}
int main()
{
SqStack s;
Elemtype e;
printf("初始化栈\n");
InitStack(&s);
printf("a, b, c, d, e, f进行进栈操作\n");
Push(&s, 'a');
Push(&s, 'b');
Push(&s, 'c');
Push(&s, 'd');
Push(&s, 'e');
Push(&s, 'f');
Push(&s, 'g');
printf("显示栈中的内容");
DispStack(s);
Pop(&s, &e);
printf("弹栈操作 %c\n", e);
Pop(&s, &e);
printf("弹栈操作 %c\n", e);
printf("显示栈中内容\n");
DispStack(s);
GetTop(s, &e);
printf("显示栈顶元素%c \n",e);
system("pause");
}