数据结构之小括号匹配

//此程序能够判断一系列小括号匹配问题,其中可以加入一些其他字符例如(3+4)—((7-9)
#include<windows.h>
#include<stdio.h>
#define MaxSize 50
#define DataType char
const int MAXSIZE = 100;//栈和队列的最大容量
typedef struct//栈结构体
{
    DataType elem[MAXSIZE];
    int top;
}SqStack;
void InitStack(SqStack &s)//初始化栈
{
    s.top = 0;
}
bool Push(SqStack &s, DataType x)//向栈中加入一个数据元素
{
    if (s.top == MAXSIZE)//判满
        return false;
    else
    {
        s.elem[s.top++] = x;//top永远在栈顶元素上一个
        return true;
    }
}
bool Pop(SqStack &s, DataType &x)//从栈中输出一个数据元素(栈顶),并删除
{
    if (s.top != 0)
    {
        x = s.elem[--s.top];
        return true;
    }
    else    //判空
    {
        printf("Underflow!\n");
        return false;
    }
}
bool StackEmpty(SqStack s)//判断是否为空栈
{
    if (s.top == 0)
        return true;
    return false;
}
bool GetTop(SqStack s, DataType &x)//获取栈顶元素,不删除
{
    if(s.top==0)
        return false;
    x = s.elem[s.top - 1];
    return true;
}
bool func()
{
    SqStack mystack;
    InitStack(mystack);
    char c=getchar();
    while(c!='\n')
    {
        if(c=='(')
            Push(mystack,c);
        else if(c==')')
        {
            
            if(!Pop(mystack,c))//此处也可以在之前不定义bool型的Pop,而此处改用判断是否为空 ,再弹出
                return false;//一个函数既判断了能否弹出,又实现了弹出
            /*if (StackEmpty(mystack))
                return false;
                Pop...
            */        
        }
        c=getchar();
    }
    if (StackEmpty(mystack))
                return true;
    else
        return false;
}
int main()
{
    
    printf("请输入一系列小括号以用来判匹配:\n");
    if(func())
        printf("匹配!\n");
    else
        printf("不匹配!\n");
    system("pause");
}

  如果加入中括号和大括号则需要进行更复杂的匹配设定,不过还是基于此。

posted @ 2016-07-27 10:09  王毅2016  阅读(389)  评论(0编辑  收藏  举报