王道数据结构思维导图8:栈
顺序栈基本操作
typedef struct{
//初始化栈
ElemType data[MaxSize];
int top;
}SqStact;
//进栈
//s.top=-1
bool Push(SqStact &s,ElemType &x){
if(s.top==Maxsize-1)
return false;
//先加1,或赋值
s.top++;
s.data[s.top]=x;
return true;
}
//s.top=0
bool Push(SqStact &s,ElemType &x){
if(s.top==Maxsize-1)
return false;
//先赋值,在加1
s.data[s.top]=x;
s.top++;
return true;
}
//出栈
//s.top=-1;
bool Pop((SqStact &s,ElemType &x) {
if(s.top==-1)
return false;
x=s.data[s.top];
s.top=s.top-1;
return true;
}
//s.top=0;
bool Pop((SqStact &s,ElemType &x) {
if(s.top==-1)
return false;
s.top=s.top-1;
x=s.data[s.top];
return true;
}
栈在括号匹配中应用
bool barcketCheck(char str(),int length){
//初始化一个栈
SqStack S;
InitStack(S)
for(int i=0;i<length;i++){
if(str[i]=='('||'['||'{'){
Pop(S,str[i]);
}else{
//判断栈是否为空
if(StackEmpty(S))
return false;
//topElem为栈顶元素
char topElem;
Pop(S,topElem);
if(ste[i]=')'&&topElem!='(')
return false;
if(ste[i]=']'&&topElem!='[')
return false;
if(ste[i]='}'&&topElem!='{')
return false;
}
}
return stackEmpty(S);
}