栈的定义
栈是一种只能在一端进行插入或者删除操作的线性表
栈的逻辑结构:线性表,可以插入或删除的一段叫做栈顶,另一端叫做栈底。
顺序实现
一个top指针指向栈顶
栈的top值不一定设置为-1,只要能够满足先进后出的特性即可。
元素进栈:
元素出栈:
此时,3,4虽然仍保存在数组中,但已经出栈,不属于栈内
判断栈空或栈满
#include<iostream>
using namespace std;
#define MAX 100
typedef struct{
int data[MAX];//栈中存放的元素
int top;//栈顶指针
}SqStack;
//初始化栈,设置栈顶指针位置top为-1
void InitStack(SqStack &S){
S.top = -1;
}
//判断栈是否为空
bool StackEmpty(SqStack S){
if(S.top < 0) return true;
else return false;
}
//入栈
bool pushStack(SqStack &S,int x){
if(S.top == MAX - 1) return false;
S.top++;
S.data[S.top] = x;
return true;
}
//出栈
bool popStack(SqStack &S,int &x){
if(StackEmpty(S)) return false;
x = S.data[S.top--];
return true;
}
//获取栈顶元素
bool getElem(SqStack S,int &x){
if(StackEmpty(S)) return false;
x = S.data[S.top];
return true;
}
int main(){
SqStack S;
InitStack(S);
pushStack(S,5);
pushStack(S,4);
pushStack(S,3);
pushStack(S,2);
pushStack(S,1);
int x;
popStack(S,x);
cout<<"弹出的栈顶元素为"<<x<<endl;
getElem(S,x);
cout<<"取到的栈顶元素为:"<<x<<endl;
while(S.top >= 0){
popStack(S,x);
cout<<"弹出的栈顶元素为"<<x<<endl;
}
return 0;
}
链式存储
#include<iostream>
#include<malloc.h>
using namespace std;
typedef struct LNode{
int data;//数据域
struct LNode* next;
}*LinkStack;
void InitStack(LNode *&S){
S = (LNode*)malloc(sizeof(LNode));//制造一个头结点
S->next = NULL;
}
bool StackEmpty(LNode *S){
if(S->next == NULL) return true;
else return false;
}
//链式存储中只要有足够的内存就不会栈满,所以入栈无需判断栈是否已满
void pushStack(LNode *&S,int x){
LNode *p;
p = (LNode*)malloc(sizeof(LNode));
p->next = NULL;
p->data = x;
p->next = S->next;
S->next = p;
}
//出栈
bool popStack(LNode *&S,int &x){
LNode *p;
if(StackEmpty(S)) return false;
p = S->next;
x = p->data;
S->next = p->next;
free(p);
return true;
}
//取栈顶元素
bool getElem(LNode *S,int &x){
if(StackEmpty(S)) return false;
x = S->next->data;
return true;
}
int main(){
LinkStack S;
InitStack(S);
pushStack(S,5);
pushStack(S,4);
pushStack(S,3);
pushStack(S,2);
pushStack(S,1);
int x;
popStack(S,x);
cout<<"弹出的栈顶元素为"<<x<<endl;
getElem(S,x);
cout<<"取到的栈顶元素为:"<<x<<endl;
while(S->next){
popStack(S,x);
cout<<"弹出的栈顶元素为"<<x<<endl;
}
return 0;
}
图片来源于率辉老师的数据结构课程