1.1栈的定义
栈(stack)是一种只能在一端进行插入或删除的线性表。
下面是一些基础概念:
- 栈顶(top) : 表中允许进行插入、删除操作的线性表
- 栈底(bottom):表的另一端
- 空栈 :栈中没有数据元素
- 进栈/入栈(push):栈的插入操作
- 出栈/退栈(pop):栈的删除操作
栈的抽象数据类型定义:
1.2栈的顺序存储结构
采用顺序存储结构的栈称为顺序栈。
栈中的元素相对位置是成线性的
声明:
typedef char ElemType;
typedef struct
{
ElemType data[MaxSize];
int top; //栈顶指针
}SqStack;
图示:
1.3 顺序栈基本运算
我们首先要明确几点:
- 栈满的条件:s–>top = MaxSize - 1
- 元素e的进栈操作:先将栈顶指针top增1,然后将元素e放在栈顶指针处
- 出栈操作:先将栈顶指针top处的元素取出放在e中,然后栈顶指针减1
操作图示:
(1)初始化栈
//栈的初始化
void InitStack(SqStack*& s)
{
s = (SqStack*)malloc(sizeof(SqStack));
s->top = -1;//栈顶指针置-1
}
(2)销毁栈:
//栈的销毁
void DestroyStack(SqStack*& s)
{
free(s);
}
(3)判断栈是否为空:
//栈是否为空
bool StackEmpty(SqStack* s)
{
return (s->top == -1);
}
(4)进栈:
//进栈
bool Push(SqStack*& s, ElemType e)
{
if (s->top == MaxSize -1)//栈满
return false;
s->top++; //栈顶指针增一
s->data[s->top] = e; //元素e放在栈顶指针处
return true;
}
(5)出栈:
bool Pop(SqStack*& s, ElemType& e)
{
if (s->top == -1)
return false;
e = s->data[s->top];//取栈顶元素
s->top--;
return true;
}
(6)取栈顶元素:
bool GetTop(SqStack* s, ElemType& e)
{
if (s->top == -1)
return false;
e = s->data[s->top];
return true;
}
顺序栈的完整代码如下:
#include<iostream>
using namespace std;
#define MaxSize 50
typedef char ElemType;
typedef struct
{
ElemType data[MaxSize];
int top; //栈顶指针
}SqStack;
//栈的初始化
void InitStack(SqStack*& s)
{
s = (SqStack*)malloc(sizeof(SqStack));
s->top = -1;//栈顶指针置-1
}
//栈的销毁
void DestroyStack(SqStack*& s)
{
free(s);
}
//栈是否为空
bool StackEmpty(SqStack* s)
{
return (s->top == -1);
}
//进栈
bool Push(SqStack*& s, ElemType e)
{
if (s->top == MaxSize -1)//栈满
return false;
s->top++; //栈顶指针增一
s->data[s->top] = e; //元素e放在栈顶指针处
return true;
}
bool Pop(SqStack*& s, ElemType& e)
{
if (s->top == -1)
return false;
e = s->data[s->top];//取栈顶元素
s->top--;
return true;
}
bool GetTop(SqStack* s, ElemType& e)
{
if (s->top == -1)
return false;
e = s->data[s->top];
return true;
}
int main() {
SqStack* st;
ElemType e;
ElemType s[] = "abcba";
return 0;
}