Description
假设一个算术表达式中可以包含三种括号:圆括号“( ”和“ )”、方括号“ [ ”和“ ] ”和花括号“{”和“}”,且这三种括号可按任意的次序嵌套使用(如:…[…{…}…[…]…]…[…]…(…)…)。编写判别给定表达式中所含括号是否正确配对出现的程序(已知表达式已存入数据元素为字符的顺序表中)。
Input
输入算术表达式,换行结束。
Output
若给定表达式中所含括号正确配对,则输出yes,否则输出no。
- Sample Input
[5+(6-3)]-(2+3)]
- Sample Output
no
基本思路就是利用栈遍历字符串,将括号单独考虑,遇到左括号则将其压入栈中,遇到右括号则与栈顶括号进行匹配,若能匹配则栈顶出栈,继续遍历;若不符合则输出’no’结束;当遍历结束后检查栈是否为空,若为空则表示全部匹配,输出’yes’,不为空则输出’no’。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct list
{
char num;
struct list* next;
}list;
typedef struct stack
{
list* ptop;
list* pbottom;
}stack;
void init(stack* pstack);
void push(stack* pstack,int value);
void pop(stack* stack);
//栈的初始化
void init(stack* pstack)
{
pstack->pbottom = (list* )malloc(sizeof(list));
if(pstack->pbottom == NULL)
{
printf("内存分配失败,程序退出");
exit(1);
}
else
{
pstack->ptop = pstack->pbottom;
pstack->pbottom->next = NULL;//将栈底最后一个元素的下一个指针设为NULL
}
}
//将某个元素压入栈中
void push(stack* pstack,char value)
{
list* pnew = (list* )malloc(sizeof(list));
pnew->num = value;
pnew->next = pstack->ptop;
pstack->ptop = pnew;
}
//栈顶元素出栈
void pop(stack* stack)
{
list* p;
p = stack->ptop;
stack->ptop = stack->ptop->next;
free(p);
}
//输入字符串
int main()
{
stack* s;
s = (stack*)malloc(sizeof(stack));
char x[1000];
char sign[100];
int k = 0;
scanf("%s",x);
for(int i = 0;i < strlen(x);i++)
{
if(x[i] == '('||x[i] == ')'||x[i] == '['||x[i] == ']'||x[i] == '{'||x[i] == '}')
{
sign[k] = x[i];
k++;
}
}
init(s);
for(int i = 0;i < strlen(sign);i++)
{
if(sign[i] == '('||sign[i] == '['||sign[i] == '{')
{
push(s,sign[i]);
}
if(sign[i] == ')')
{
if(s->ptop->num == '(')
{
pop(s);
}
else
{
printf("no\n");
return 0;
}
}
if(sign[i] == ']')
{
if(s->ptop->num == '[')
{
pop(s);
}
else
{
printf("no\n");
return 0;
}
}
if(sign[i] == '}')
{
if(s->ptop->num == '{')
{
pop(s);
}
else
{
printf("no\n");
return 0;
}
}
}
if(s->ptop == s->pbottom)
{
printf("yes\n");
return 0;
}
}