问题描述
从左至右扫描一个字符串(或表达式),则每个右括号将与最近遇到的那个左括号相匹配。
思路
用栈结构储存表达式,当遇到配对符号时弹出栈顶符号和匹配符号配对。当符号配对成功则继续配对直到栈空;当匹配失败则返回
代码
#include<stdio.h>
#include <malloc.h>
#include <string.h>
typedef struct Node* PtrNode;
struct Node
{
char data;
PtrNode next;
};
typedef PtrNode Stack;
Stack create()
{
Stack s;
s = (Stack)malloc(sizeof(struct Node));
s->next = NULL;
return s;
}
bool is_empty(Stack s)
{
return (s->next == NULL);
}
bool Push(Stack stack, char data)
{
PtrNode tmpcell;
tmpcell = (PtrNode)malloc(sizeof(struct Node));
tmpcell->data = data;
tmpcell->next = stack->next;//tmp指向stack头结点后面的结点
stack->next = tmpcell;
return true;
}
int pop(Stack s)
{
PtrNode firstcell;
int topelement;
if (is_empty(s))
{
printf_s("empty");
}
else
{
firstcell = s->next;
topelement = firstcell->data;
s->next = firstcell->next;
free(firstcell);
return topelement;
}
return 0;
}
Stack to_top(Stack s)
{
while (s->next != NULL)
{
s = s->next;
}
return s;
}
bool judge(char* str, int size)
{
Stack stack,p;
char leftsig;
p = create();
for (int i = 0; i < size; i++)
{
char ch = str[i];
switch (ch)
{
case '(':
case '[':
case '{':
Push(p, str[i]);
break;
case')':
case']':
case'}':
leftsig = (char)p->data;
pop(p);
if (leftsig == '(' && str[i] != ')')
{
return false;
}
if (leftsig == '[' && str[i] != ']')
{
return false;
}
if (leftsig == '{' && str[i] != '}')
{
return false;
}
default:
break;
}
}
if (!is_empty(p))
{
return false;
}
else
{
printf_s("匹配成功");
return true;
}
}
int main()
{
char seq[] = {"{[](aaa)}" };
int len = strlen(seq);
judge(seq, len);
}
参考
https://blog.csdn.net/qq_39478237/article/details/81974025