栈的应用实例——平衡符号

检查()、[]、{}是否配对。

/* stack_balance_symbol */

#include "stack.h"
#include <stdio.h>
#include <stdlib.h>
#include <error.h>

int
main(int argc, char **argv)
{
    FILE *fp;
    stack s;
    char c;
    char ctmp;    

    if(argc != 2)
    {
        printf("usage: a.out <filename>
");
        exit(0);
    }
    
    fp = fopen(argv[1], "r");
    if(fp == NULL)
    {
        perror("fopen");
        exit(1);
    }

    s = create_stack( 10 );
    c = fgetc(fp);
    while(c != EOF)
    {    
        switch(c)
        {
            case '(':
                push(c, s);
                break;
            case ')':
                ctmp = top_and_pop( s );
                if(ctmp != '(')
                    printf("not match!
");
                break;    
            case '{':
                push(c, s);
                break;
            case '}':
                ctmp = top_and_pop( s );
                if(ctmp != '{')
                    printf("not match!
");
                break;    
            case '[':
                push(c, s);
                break;
            case ']':
                ctmp = top_and_pop( s );
                if(ctmp != '[')
                    printf("not match!
");
                break;    
        }
        c = fgetc(fp);
    }
    
    if(is_empty( s ))
        printf("match
");
    else
        printf("not match
");
}

上面的程序中所使用的stack.h参考http://www.cnblogs.com/nufangrensheng/p/3610520.html。(注:stack.h中使用的是

typedef char element_type;

测试结果:

image

原文地址:https://www.cnblogs.com/nufangrensheng/p/3610598.html