栈相关代码
Stack.h
//
// Stack.hpp
// FirstP
//
// Created by 赫赫 on 2023/11/1.
// 这里主要记录一下顺序栈#ifndef Stack_hpp
#define Stack_hpp
#define MaxSize 10#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>#endif /* Stack_hpp */typedef struct{int data[MaxSize];int top;//栈顶指针
}SqStack;//初始化栈
void InitStack(SqStack &S);//入栈
bool Push(SqStack &S,int elem);//出栈
bool Pop(SqStack &S,int &elem);//出栈
bool Pop(SqStack &S,char &elem);//读栈顶元素
bool GetTop(SqStack &S,int &elem);//用栈来实现表达式的括号匹配
bool bracketCheck(char str[],int length);//---------------------------------
//共享栈的结构体定义
typedef struct{int data[MaxSize];int top0;//栈顶指针int top1;
}SqShareStack;//初始化共享栈
void InitShareStack(SqShareStack &S);
Stack.cpp
//
// Stack.cpp
// FirstP
//
// Created by 赫赫 on 2023/11/1.
//#include "Stack.hpp"//初始化栈
void InitStack(SqStack &S){S.top=-1;//初始化栈顶指针
}//入栈
bool Push(SqStack &S,int elem){if(S.top==MaxSize-1){return false;}else{S.top+=1;S.data[S.top]=elem;return true;}
}//出栈
bool Pop(SqStack &S,int &elem){if(S.top==-1){return false;}else{elem=S.data[S.top];S.top-=1;return true;}
}bool Pop(SqStack &S,char &elem){if(S.top==-1){return false;}else{elem=S.data[S.top];S.top-=1;return true;}
}//读栈顶元素
bool GetTop(SqStack &S,int &elem){if(S.top==-1){return false;}else{elem=S.data[S.top];return true;}
}//用栈来实现括号表达式的匹配
bool bracketCheck(char str[],int length){SqStack S;InitStack(S);for(int i=0;i<length;i++){if(str[i]=='('||str[i]=='['||str[i]=='{'){Push(S,str[i]);}else{if(S.top==-1){//栈空return false;}char topElem;Pop(S,topElem);if(str[i]==')'&&topElem!='('){return false;}if(str[i]==']'&&topElem!='['){return false;}if(str[i]=='}'&&topElem!='{'){return false;}}}if(S.top==-1){//栈空return true;}else{return false;}
}//初始化共享栈
void InitShareStack(SqShareStack &S){S.top0=-1;S.top1=MaxSize;//当top0+1=top1时共享栈满
}