一-栈
1-概念
栈是只允许在一端进行插入或删除操作的线性表
后进先出(LIFO)
2-顺序存储实现
//定义一个栈
#define MaxSize 10
typedef struct{
ElemType data[MaxSize];
//栈顶指针
int top;
}SqStack;
//初始化栈,栈顶指针也可以初始化为0
void InitStack(SqStack &S){
S.top=-1;
}
//进栈
bool Push(SqStack &S, ElemType x){
//栈满
if(S.top==MaxSize-1)
return false;
//元素进栈,等价于S.data[++S.top]=x;
S.top = S.top + 1;
S.data[S.top]=x;
return true;
}
//出栈
bool Pop(SqStack &S, ElemType &x){
//栈空
if(S.top==-1)
return false;
//栈顶元素先出栈,等价于x=S.data[S.top--];
x=S.data[S.top];
S.top=S.top-1;
return true;
}
//读取栈顶元素
bool GetTop(SqStack &S, ElemType &x){
if(S.top==-1)
return false;
x=S.data[S.top];
return false;
}
void testStack(){
SqStack S;
InitStack(S);
}
共享栈:两个栈共享同一片内存空间,两个栈从两边往中间增长
//定义
#define MaxSize 10
typedef struct{
ElemType data[MaxSize];
//0号栈
int top0;
//1号栈
int top1;
}SqStack;
//初始化
void InitStack(ShStack &S){
S.top=-1;
S.top=MaxSize;
}
//栈满条件
top0 + 1 == top1
3-链式存储实现
类似于单链表,单链表有头插法和尾插法,栈的实现是只有头插法。
二-队列
1-概念
只允许在一端进行插入,在另一端删除的线性表
先进先出(FIFO)
2-顺序实现(循环队列)
//定义
#define MaxSize 10
typedef struct{
ElemType data[MaxSize];
//队头指针和队尾指针
int front,rear;
}SqQueue;
//初始化
void InitQueue(SqQueue &Q){
Q.rear=Q.front=0;
}
void testQueue(){
SqQueue Q;
}