一.栈的符号匹配
1.方法构成
/*******************************
* 栈的应用:符号的匹配
* *********************************/
#include "顺序栈.cpp"
#include <iostream>
//#include<stdlib.h>
#include <cstring>
using namespace std;
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(str[i] == ')' || str[i] == ']' || str[i] == '}')
{
if (StackEmpty(S))
return false;
char topStr;
//出栈元素
Pop(S, topStr);
//判断
if (str[i] == ')' && topStr != '(')
return false;
if (str[i] == '[' && topStr != '[')
return false;
if (str[i] == '}' && topStr != '{')
return false;
}
}
return StackEmpty(S);
}
int getLen(char str[])
{
return strlen(str);
}
int main()
{
char str[] = "a+(b+(c+d))()";
int len = getLen(str);
// SqStack S;
// InitStack(S);
// cout<<S.top<<endl;
// char ch='a';
// Push(S, ch);
// cout<<S.top<<endl;
// char val;
// Pop(S,val);
// cout<<S.top<<endl;
// cout<< val<<endl;
int flag = bracketCheck(str, len);
cout<<flag<<endl;
if (flag)
cout << "匹配成功" << endl;
else
cout << "字符串不符合" << endl;
return 0;
}
2.结构体选择
选择基本的顺序栈作为方法容器
//顺序栈
#include <iostream>
using namespace std;
// 1.struct init 统一写法//////////////////////////////////////////////////
#define MaxSize 10
typedef struct
{
char data[MaxSize]; //静态数组存放元素
int top; //栈顶指针top指向栈顶元素
} SqStack;
SqStack S;
// 2.init 初始化栈与判空///////////////////////////////////////////////////////
void InitStack(SqStack &S)
{
S.top = -1;
}
bool StackEmpty(SqStack S)
{
if (S.top == -1)
return true;
else
return false;
}
// 3.进栈///////////////////////////////////////////////////////
bool Push(SqStack &S, char e)
{
//完备性判断
if (S.top == MaxSize - 1) //表明栈满,无法入栈
return false;
S.data[++S.top] = e; //入栈操作,栈顶指针+1,元素入数组
return true;
}
// 4.出栈///////////////////////////////////////////////////////
bool Pop(SqStack &S, char &x)
{
//用来记录出栈的元素
if (S.top == -1)
return false;
x = S.data[S.top--];
return true;
}
// 5.读取操作
bool GetTop(SqStack S, char &e)
{
if (S.top == -1)
return false;
e = S.data[S.top];
return true;
}