本文代码为学习总结,如果错误敬请指正!感谢各位大佬 😃
历史文章
1.1线性表的顺序表示(顺序表)
1.2线性表的链式表示(单链表)
1.3线性表的链式表示(双链表)
1.4线性表的链式表示(循环单链表)
栈的定义
只允许在一端进行插入或删除操作的线性表
栈的操作特性:后进先出(LIFO)
顺序栈的基本操作
顺序存储类型描述
#define MaxSize 100 //定义栈中元素的最大个数
typedef int ElemType;
typedef struct {
ElemType data[MaxSize];//存放栈中元素
int top;//栈顶指针
}SqStack;
栈顶指针:S.top,初始时设置S.top==-1,栈顶元素:S.data[S.top]
栈空条件:S.top==-1
栈满条件:S.data==MaxSize-1
栈长:S.top+1
初始化
//初始化
void InitStack(SqStack &S){
S.top=-1;//初始化栈顶指针
}
判栈空
栈空条件:S.top==-1
//判栈空
bool StackEmpty(SqStack S){
if(S.top==-1){
return true;
}else{
return false;
}
}
进栈
进栈操作:栈不满时,栈顶指针先+1,再送值到栈顶
//进栈
bool Push(SqStack &S,ElemType x){
if(S.top==MaxSize-1){//栈满
return false;
}
S.top++;//指针指向下一个位置
S.data[S.top]=x;//入栈
return true;
}
出栈
出栈操作:栈非空时,先取栈顶元素,再将栈顶指针-1
//出栈
bool Pop(SqStack &S,ElemType &x){
if(S.top==-1){//栈空
return false;
}
x=S.data[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 true;
}
完整代码及运行结果
代码
#include<stdlib.h>
#include<stdio.h>
#define MaxSize 100 //定义栈中元素的最大个数
typedef int ElemType;
typedef struct {
ElemType data[MaxSize];//存放栈中元素
int top;//栈顶指针
}SqStack;
//初始化
void InitStack(SqStack &S){
S.top=-1;//初始化栈顶指针
}
//判栈空
bool StackEmpty(SqStack S){
if(S.top==-1){
return true;
}else{
return false;
}
}
//进栈
bool Push(SqStack &S,ElemType x){
if(S.top==MaxSize-1){//栈满
return false;
}
S.top++;//指针指向下一个位置
S.data[S.top]=x;//入栈
return true;
}
//出栈
bool Pop(SqStack &S,ElemType &x){
if(S.top==-1){//栈空
return false;
}
x=S.data[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 true;
}
int main(){
SqStack Sq;
InitStack(Sq);
int i=0;
ElemType e;
printf("请输入进栈的元素,以62757结束:");
scanf("%d",&e);
while(e!=62757){
Push(Sq,e);
scanf("%d",&e);
}
printf("元素依次出栈:");
while(Sq.top!=-1){
Pop(Sq,e);
printf("%d ",e);
}
}
运行结果
请输入进栈的元素,以62757结束:12 32 2 13 83 26 62757
元素依次出栈:26 83 13 2 32 12