[数据结构]括号匹配 解题报告

Problem Description

假设一个算术表达式中包含圆括号、方括号两种类型的括号,试编写一个判断表达式中括号是否匹配的程序,匹配返回Match succeed!,否则返回Match false!

[1+2*(3+4*(5+6))]括号匹配
(1+2)*(1+2*[(1+2)+3)括号不匹配
输入

包含圆括号、方括号两种类型括号的算术表达式
输出

匹配输出Match succeed!
不匹配输出 Match false!

输入[1+2* (3+4*(5+6))]
输出Match succeed!


测试输入

[1+2*(3+4*(5+6))]

测试输出

Match succeed!

AcCode

//
//  main.cpp
//  括号匹配
//
//  Created by jetviper on 2017/3/26.
//  Copyright © 2017年 jetviper. All rights reserved.
//


#include 
#include 
#include 
#include
#define true 1
#define false 0

typedef struct Node
{
    char data;
    struct Node *pNext;
}NODE, *PNODE;

typedef struct Stack
{
    PNODE pTop;
    PNODE pBottom;
}STACK, *PSTACK;
//栈的初始化
void init(PSTACK pS)
{
    pS->pTop = (PNODE)malloc(sizeof(NODE));
    pS->pBottom = pS->pTop;
    pS->pTop->pNext = NULL;
    return;
}
//插入元素到栈顶
void push(PSTACK pS, char val)
{
    PNODE pNew = (PNODE)malloc(sizeof(NODE));
    pNew->data = val;
    pNew->pNext = pS->pTop;
    pS->pTop = pNew;
    return;
}
//判断栈是否为空
int empty(PSTACK pS)
{
    if (pS->pTop == pS->pBottom)
    {
        return true;
    }
    else
        return false;
}

void deltop(PSTACK pS) {
    pS->pTop = pS->pTop->pNext;
    return;
}

int main(void)
{
    STACK S;
    PSTACK ps=&S;
    init(&S);
    char val;
    char str[100];
    scanf("%s", &str);
    for (int i = 0; i < strlen(str); i++) {
        if (str[i] == '(' || str[i] == ')' || str[i] == '[' || str[i] == ']') {
            val = ps->pTop->data;
            
            if (str[i] == '(' || str[i] == '[')push(&S, str[i]);
            else if (val=='(' && str[i]==')'||val=='['&&str[i]==']')deltop(&S);
            else push(&S, str[i]);
        }
    }
    
    if (empty(&S))
    {
        printf("Match succeed!\n");
    }
    else
    {
        printf("Match false!\n");
    }
    
    return 0;
}

你可能感兴趣的:([数据结构]括号匹配 解题报告)