用顺序栈判断()、{}、[]是否匹配

    将所有左括号进栈,在遇到右括号时取出栈顶元素,若匹配则出栈栈顶元素,进行一次判断,若不匹配则括号不匹配。

//"标头.h"
#pragma once
#include<iostream>
#define Max 100
using namespace std;
typedef char Elem;
typedef struct SqStack
{
    Elem data[Max];
    int top;
}Stack;
void InitStack(Stack *s)//初始化
{
    s = new Stack;
    s->top = -1;
}
bool Push(Stack *p,Elem e)//进栈
{
    if (p->top == Max - 1)
        return false;
    p->top++;
    p->data[p->top] = e;
    return true;
}
bool Pop(Stack *p, Elem &e)//出栈
{
    if (p->top == -1)
        return false;
    e = p->data[p->top];
    p->top--;
    return true;
}
bool GetTop(Stack *p, Elem &e)//取栈顶指针
{
    if (p->top == -1)
        return false;
    e = p->data[p->top];
    return true;
}
bool Empty(Stack *s)//判断栈是否为空
{
    return (s->top == -1);
}
void Destory(Stack *s)//销毁
{
    free(s);
}
bool PanDuan(char *str)//判断是否匹配
{
    bool match = true;
    Elem e;
    Stack *s;
    s = new Stack;
    s->top = -1;
    while (*str != '\0'&&match)
    {
        switch (*str)
        {
        case '(':
        case '{':
        case '[':
            Push(s, *str);//将左括号全部进栈
            break;
        case ')':
            if (GetTop(s, e) == true)
            {
                if (e != '(')
                    match = false;
                else
                {
                    Pop(s, e);
                }
                break;
            }
            else
                match = false;
            break;
        case '}':
            if (GetTop(s, e) == true)
            {
                if (e != '{')
                    match = false;
                else
                {
                    Pop(s, e);
                }
                break;
            }
            else
                match = false;
            break;
        case ']':
            if (GetTop(s, e) == true)
            {
                if (e != '[')
                    match = false;
                else
                {
                    Pop(s, e);
                }
                break;
            }
            else
                match = false;
            break;
        default:
            break;
        }
        *str++;
    }
    if (!Empty(s))
        match = false;
    Destory(s);
    return match;
}
#include"标头.h"
int main()
{
	char str[] = "[(})]";
	bool match=PanDuan(str);
	cout << "括号是否匹配" << match << endl;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值