/**
* 思路:
* 扫描到左括号时进栈
* 扫描到右括号时 先判断是否栈空 是则match false
* 否则弹出栈顶元素与当前扫描的括号进行匹配 不符合则match false
* 循环扫描完成后 判断栈中是否还有元素 是则 match false 否true
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
//定义链栈结构体
typedef struct Stack {
char data;
struct Stack *next;
} node;
初始化栈
node *initStack(node *top) {
top = malloc(sizeof(node));
top->next = NULL;
return top;
}
判断是否栈空
bool isEmpty(node *top) {
return top->next == NULL ? true : false;
}
/压栈操作
node *pushStack(node *top, char data) {
node *newNode = malloc(sizeof(node));
newNode->data = data;
newNode->next = NULL;
newNode->next = top->next;
top->next = newNode;
return top;
}
/弹栈操作
node *popStack(node *top, char *popElement) {
if (isEmpty(top)) {
return top;
}
node *popNode = top->next;
*popElement = popNode->data;
top->next = popNode->next;
free(popNode);
return top;
}
/匹配算法
int matchBracket(node* top) {
char popElement;
char i;
printf("input:");
do {
scanf("%c", &i);
if (i == '\n'){
break;
}
switch (i) {
case '(':
case '{':
case '[':
pushStack(top, i);
break;
case ']':
case '}':
case ')':
if (isEmpty(top)) {
printf("match false!\n");
return -1;
}
popStack(top, &popElement);
if ((popElement == '(' && i != ')') || (popElement == '[' && i != ']') ||
(popElement == '{' && i != '}')) {
printf("match false!\n");
return -1;
}
break;
}
}while (i != '\n');
if (isEmpty(top)) {
printf("match true!");
return 0;
} else {
printf("match false!");
return -1;
}
}
int main() {
///初始化一个栈
node *top = initStack(top);
matchBracket(top);
return 0;
}
07-19
787
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-04
1639
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-31
1380
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-29
4089
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)