【数据结构】NOJ007 表达式括号匹配

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值