码迷,mamicode.com
首页 > 其他好文 > 详细

习题3.18 检测平衡符号(/* */ 不知怎么做)

时间:2015-07-12 17:05:33      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
/* 检测平衡符号 */
#include<stdio.h>
#include<stdlib.h>

struct stack;
typedef struct stack * PtrToStack;
struct stack{
    char *Array;
    int TopOfStack;
    int Capacity;
};
PtrToStack
CreateStack( int MaxSize )
{
    PtrToStack p;
    p = malloc(sizeof(struct stack));
    p->Array = malloc(sizeof(char) * MaxSize );
    p->Capacity = MaxSize;
    p->TopOfStack = -1;
    return p;
}
int
IsEmpty( PtrToStack s)
{
    return s->TopOfStack == -1;
}
void
Pop( PtrToStack s )
{
    if( !IsEmpty( s ) )
        s->TopOfStack--;
    else
        printf("error");
}
char
Top( PtrToStack s )
{
    if( !IsEmpty( s ) )
        return s->Array[s->TopOfStack];
    else
        printf("error");
}

int
IsFull( PtrToStack s )
{
    return s->TopOfStack == s->Capacity-1;
}

void
Push( char ch, PtrToStack s)
{
    if( !IsFull(s) )
        s->Array[++s->TopOfStack] = ch;
    else
        printf("error");
}
//遇到开放符号栈空,遇到开放符号不匹配,读入完成,栈不空
int main()
{
    int MaxSize = 10;
    char tmp;
    PtrToStack s;
    s = CreateStack( MaxSize );
    while( ( tmp = getchar() ) != # )
    {
        if( tmp == ( || tmp == { || tmp == [)
            Push( tmp, s );
        else
        {
            if( IsEmpty(s) ){
                printf("error1");
                return 0;
            }
            else
            {
                switch( tmp )
                {
                    case ]:
                        if(Top(s) != [)
                        {
                            printf("error2");
                            return 0;
                        }
                        break;
                    case ):
                        if(Top(s) != ( )
                        {
                            printf("error2");
                            return 0;
                        }
                        break;
                    case }:
                        if(Top(s) != {)
                        {
                            printf("error2");
                            return 0;
                        }
                        break;
                }//switch
                Pop(s);
            }//else
        }//else
    }//while
    if(s->TopOfStack != -1)
    {
        printf("error3");
        return 0;
    }
}
View Code

 注意该算法3个error:1.读到封闭符号时,栈空error1

           2.读到#栈非空error2

          3.读到封闭符号,栈非空,可是不对应error3

习题3.18 检测平衡符号(/* */ 不知怎么做)

标签:

原文地址:http://www.cnblogs.com/gabygoole/p/4641106.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!