#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef char ElemType;
//栈的顺序存储
typedef struct node {
ElemType data;
struct node* next;
}SNode, *Stack;
void init(Stack &s)
{
s = (Stack)malloc(sizeof(SNode));
s->next = NULL;
}
bool isEmpty(Stack &s)
{
return (s->next == NULL);
}
void push(Stack &s, ElemType x)
{
SNode* tmp = (Stack)malloc(sizeof(SNode));
tmp->data = x;
tmp->next = s->next;
s->next = tmp;
}
ElemType getTop(Stack &s)
{
return s->next->data;
}
void pop(Stack &s)
{
SNode* tmp = s->next;
s->next = s->next->next;
free(tmp);
}
int main()
{
//初始化栈
Stack s;
init(s);
ElemType c;
bool flag = true;
//不断输入字符,直到遇到换行为止
while((c=getchar()) && (c!='\n')) {
//遇到左括号就入栈
if(c=='{' || c=='[' || c=='(')
push(s, c);
//遇到右括号,先判断栈是否为空
else if(c=='}' || c==']' || c==')') {
if(isEmpty(s)) { //如果为空,退出
flag = false;
break;
}
else { //不为空,则获取栈顶元素,看是否匹配
ElemType stop = getTop(s);
pop(s);
if((stop=='{' && c!='}') ||
(stop=='[' && c!=']') ||
(stop=='(' && c!=')'))
{
flag = false; //不匹配,退出
break;
}
}
}
}
//如果所有字符都输入完了,栈里还不空,证明还有多余的括号,不匹配
if(!isEmpty(s))
flag = false;
//输出
if(flag)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
return 0;
}
【数据结构】NOJ007 表达式括号匹配
最新推荐文章于 2022-05-09 20:02:07 发布