栈的应用实践——括号匹配的检验

目的:检验一个字符串中的大括号,中括号,小括号是否匹配。
方法:数据结构c语言版提出的期待的急迫程度描述这个问题,具体的思路为:
处于栈顶的括号总是最急迫的期待着和下一个读入的括号进行匹配
如果下一个括号可以匹配,那么栈顶括号出栈,之后新的栈顶处于最急迫的地位,或者空栈继续读入;
如果下一个括号不可以匹配栈顶,则这个括号进栈并成为新的栈顶,成为最急迫的元素,原先的急迫度则降了一级。
可以预知的是,若是字符串中括号最终可以匹配,读取所有字符后,栈将为空,可以以此作为判断的最终条件。

写的不规范之处,还请指出,见谅。

//Main idea
//Pushing a bracket A into a stack,
//if the bracket A cannot match the bracket B in top of the stack
//However,if they can match each other,not only A cannot pushed into stack
//but B will be popped from the stack.

#include
#include
#include
typedef struct Node
{
    char bracket;
    struct Node *next;
}StackNode; //define the Node of stack

int emptystack(StackNode *);//Judge if it is a empty or not
StackNode *push(StackNode *,char);//push a character in stack
StackNode *pop(StackNode *);//pop the character that is in top
StackNode *creatstack();//initalize a stack
int judgecharacter(char);//judge if a character is a bracket or not
int judgematching(char,char);//judge if two bracket can match each other or not

int main(int argc,char *argv[])
{
    if (argc!=2)
    {
        printf("True Usage:bracket String\n");
        exit(0);
    }
    //Make sure that there are two command line parameters
    StackNode *s=creatstack();//get a empty stack
    int i;
    for(i=0;i<strlen(argv[1]);i++)//string traversal
    {
        if(judgecharacter(argv[1][i]))//find bracket
        {
            //first bracket in stack,but if the string don't include any bracket,
            //the final outcome is that brackets are matched
            if(emptystack(s))       
                s=push(s,argv[1][i]);
            else
                {
                    if(judgematching(s->bracket,argv[1][i]))
                        s=pop(s);
                    else
                        s=push(s,argv[1][i]);
                }
        }
    }
    if(emptystack(s))
        printf("Brackets are matched in this string\n");
    else
        printf("Brackets are not matched\n");
    return 0;
}

int emptystack(StackNode *s)
{
    if(s->next==NULL)
        return 1;
    else
        return 0;
}

StackNode *push(StackNode *s,char e)
{
    StackNode *new=(StackNode *)malloc(sizeof(StackNode));
    new->next=s;
    new->bracket=e;
    return new;
}

StackNode *pop(StackNode *s)
//In main function,we have considered that stack is empty
//so ,now we can ignore this case
{
    StackNode *temp=s->next;
    free(s);
    return temp;
}

StackNode *creatstack()
//creat a empty stack which include one node
{
    StackNode *s=(StackNode *)malloc(sizeof(StackNode));
    s->next=NULL;
    return s;
}

int judgecharacter(char h)
{
    if(h=='['||h==']'||h=='{'||h=='}'||h=='('||h==')')
        return 1;
    else
        return 0;
}

int judgematching(char w,char f)
//please notice that position is different between w and f
{
    if((w=='{'&&f=='}')||(w=='['&&f==']')||(w=='('&&f==')'))
        return 1;
    else
        return 0;

}

用法应该在终端下,给予命令行参数。自己测试的第二个参数字符串需要用双引号括起。

你可能感兴趣的:(C)