2.3.1 栈在括号匹配中的应用
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#define true 1;
#define false 0;
#define MaxSize 50
typedef struct {
char data[MaxSize];
int top;
} SqStack;
void InitStack(SqStack *S){
S->top=-1;
}
int StackEmpty(SqStack *S){
if(S->top==-1) {return true; }
else {return false;}
}
int Push (SqStack *S,char x){
if(S->top==MaxSize-1)
return false;
S->data[++S->top]=x;
return true;
}
int Pop (SqStack *S,char *x){
if(S->top==-1)
return false;
*x=S->data[S->top--];
return true;
}
int GetTop(SqStack *S,char x){
if(S->top==-1)
return false;
x=S->data[S->top--];
return true;
}
int Destroy(SqStack *S){
S->top=-1;
return 1;
}
int bracketCheck(char str[],int len){
SqStack S;
InitStack(&S);
for (int i = 0; i < len; i++)
{
if (str[i]=='('||str[i]=='['||str[i]=='{')
{
Push(&S, str[i]);
}else
{
if (StackEmpty(&S))
{
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;
}
}
return StackEmpty(&S);
}
int main(){
char str1[] = "{({{[]})}";
if (bracketCheck(str1, 10))
{
printf("match success!");
}
else
{
printf("match fail!");
}
return 0;
}
2.3.2 栈在表达式求值中的应用
2.3.3 栈在递归中的应用
2.3.4 队列在层次遍历中的应用