思想:
1.遇到左括号就入栈,遇到右括号就检查是否与左括号匹配
2.栈空左括号单身,右括号单身 左右括号不匹配--匹配失败
栈的初始化及判空
//初始化
void Init_Stack(SqStack &S)
{
S.top = -1; //初始化栈顶指针----栈顶指针指向栈顶元素--多用此方法--便于操作
//S.top=0; 若用这种方式,那么栈顶指针指向下一个元素的地址,要特别注意
}
//判空
bool Empty_Stack(SqStack &S)
{
if (S.top == -1)
return true;
else
return false;
}
栈的入栈和出栈操作
//入栈----先判满---不满则可以入栈---top先加
char Push_Stack(SqStack &S, char e)
{
if (S.top == Maxsize - 1) //栈满
return false;
S.data[++S.top] = e; //等价于 S.top++;S.data[S.top];
return true;
}
//出栈----先判空---不空则可以出栈--top后减--出栈元素用e返回
int Pop_Stack(SqStack &S, char &e)
{
if (S.top == -1)
return false;
e = S.data[S.top--]; //等价于 S.data[S.top];S.top--;
return true;
}
读入栈顶元素
//读栈顶元素---判栈空--空则无法读取
int Get_Stack(SqStack &S, char &x)
{
if (S.top == -1)
return false;
x = S.data[S.top];
return true;
}
判断括号是否匹配
//判断括号是否匹配
bool check(char str[], int length)
{
SqStack S;
Init_Stack(S);
for (int i = 0; i < length; i++)
{
if (str[i] == '(' || str[i] == '[' || str[i] == '{')
{
Push_Stack(S, str[i]);
}
else
{
if(Empty_Stack(S))
return false;
char Elem;
Pop_Stack(S, Elem);
if (str[i] == ')' && topElem != '(')
return false;
if (str[i] == ']' && topElem != '[')
return false;
if (str[i] == '}' && topElem != '{')
return false;
}
}
return Empty_Stack(S);
}
完整代码
// 括号匹配.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include<stdio.h>
#include<string.h>
#define Maxsize 100
typedef struct {
char data[Maxsize];
int top;
}SqStack;
//初始化
void Init_Stack(SqStack &S)
{
S.top = -1; //初始化栈顶指针----栈顶指针指向栈顶元素--多用此方法--便于操作
//S.top=0; 若用这种方式,那么栈顶指针指向下一个元素的地址,要特别注意
}
//判空
bool Empty_Stack(SqStack &S)
{
if (S.top == -1)
return true;
else
return false;
}
//入栈----先判满---不满则可以入栈---top先加
char Push_Stack(SqStack &S, char e)
{
if (S.top == Maxsize - 1) //栈满
return false;
S.data[++S.top] = e; //等价于 S.top++;S.data[S.top];
return true;
}
//出栈----先判空---不空则可以出栈--top后减--出栈元素用e返回
int Pop_Stack(SqStack &S, char &e)
{
if (S.top == -1)
return false;
e = S.data[S.top--]; //等价于 S.data[S.top];S.top--;
return true;
}
//读栈顶元素---判栈空--空则无法读取
int Get_Stack(SqStack &S, char &x)
{
if (S.top == -1)
return false;
x = S.data[S.top];
return true;
}
//判断括号是否匹配
bool check(char str[], int length)
{
SqStack S;
Init_Stack(S);
for (int i = 0; i < length; i++)
{
if (str[i] == '(' || str[i] == '[' || str[i] == '{')
{
Push_Stack(S, str[i]);
}
else
{
if(Empty_Stack(S))
return false;
char topElem;
Pop_Stack(S, topElem);
if (str[i] == ')' && topElem != '(')
return false;
if (str[i] == ']' && topElem != '[')
return false;
if (str[i] == '}' && topElem != '{')
return false;
}
}
return Empty_Stack(S);
}
int main()
{
char a[10];
printf("输入括号:");
gets_s(a);
printf("%s",a);
int n = strlen(a);
if (check(a, n))
{
printf("匹配成功!");
}
else
printf("失败!");
return true;
}