用c语言实现算法设计:设字符串仅有圆括号、方括号、花括号组成,仅能嵌套;使用顺序栈,编写一个算法判断是否匹配。测试“[{{()}[ ]}(){[ ]}]”, “{ [ } ]()”。
时间: 2024-05-01 10:16:33 浏览: 18
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STACK_INIT_SIZE 100
#define STACK_INCREMENT 10
typedef char ElemType;
typedef struct {
ElemType *base;
ElemType *top;
int stackSize;
} SqStack;
void InitStack(SqStack *S) {
S->base = (ElemType *) malloc(STACK_INIT_SIZE * sizeof(ElemType));
if (!S->base)
exit(0);
S->top = S->base;
S->stackSize = STACK_INIT_SIZE;
}
void Push(SqStack *S, ElemType e) {
if (S->top - S->base >= S->stackSize) {
S->base = (ElemType *) realloc(S->base, (S->stackSize + STACK_INCREMENT) * sizeof(ElemType));
if (!S->base)
exit(0);
S->top = S->base + S->stackSize;
S->stackSize += STACK_INCREMENT;
}
*(S->top++) = e;
}
ElemType Pop(SqStack *S) {
if (S->top == S->base)
exit(0);
return *(--S->top);
}
ElemType GetTop(SqStack *S) {
if (S->top == S->base)
exit(0);
return *(S->top - 1);
}
int StackEmpty(SqStack *S) {
if (S->top == S->base)
return 1;
else
return 0;
}
int Match(char left, char right) {
if (left == '(' && right == ')')
return 1;
else if (left == '[' && right == ']')
return 1;
else if (left == '{' && right == '}')
return 1;
else
return 0;
}
int main() {
SqStack S;
InitStack(&S);
char str[100];
printf("请输入一个只包含圆括号、方括号、花括号的字符串:");
scanf("%s", str);
int i, len = strlen(str);
for (i = 0; i < len; i++) {
if (str[i] == '(' || str[i] == '[' || str[i] == '{')
Push(&S, str[i]);
else if (str[i] == ')' || str[i] == ']' || str[i] == '}') {
if (!Match(Pop(&S), str[i])) {
printf("不匹配\n");
return 0;
}
}
}
if (StackEmpty(&S))
printf("匹配\n");
else
printf("不匹配\n");
return 0;
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)