实用栈检查括号是否匹配

设字符串仅由圆括号“(”和“)”,方括号“[”和“]”,花括号“{”和“}”组成,利用链栈的操作编写一个检查括号是否正确配对的算法:int Matcher(LstackTP *ls)。例如[{{()}[ ]}(){[ ]}]是正确的,而{{()[ ]}}]}则不正确。设链栈定义如下:(6分)

typedef struct node

{   char data;

struct node * next;

} LStackTp

 

//  Stack.cpp : Defines the entry point for the console application.
//

#include  " stdafx.h "
#include  " stdlib.h "


typedef  struct node
{
     char data;
     struct  node * next;
}LStackTp;


void InitStack(LStackTp **ls)
{
    *ls=NULL;
}

void Push(LStackTp **ls, char x)
{
    LStackTp *p;
    p=(LStackTp *)malloc( sizeof(LStackTp));

    p->data=x;
    p->next=*ls;
    *ls=p;
}

int Pop(LStackTp **ls, char *x)
{
    LStackTp *p;
     if (*ls!=NULL)
    {
        p=*ls;
        *x=p->data;
        *ls=p->next;
        free(p);
         return  1;
    
    }

         return  0;
}

int EmptyStack(LStackTp *ls)
{
     return (ls==NULL);
}


char GetStackTop(LStackTp *ls)
{

     if (ls)
         return ls->data;
     else
         return  ' \0 ';
}


void PrintStack(LStackTp **ls)
{
        LStackTp *p;
        p=*ls;

         while (p)
        {
            printf( " %c \n ",p->data);
            p=p->next;    
        
        }

}



int MyMatcher( char ch1, char ch2)
{
     if ((ch1== ' ( ') && (ch2== ' ) '))  return  1;
     if ((ch1== ' [ ') && (ch2== ' ] '))  return  1;
     if ((ch1== ' { ') && (ch2== ' } '))  return  1;
     return  0;
}


int Matcher(LStackTp **ls, char *p)
{
     char ch;
     char *x=&ch;
     while (*p)
    {
         if ( MyMatcher(GetStackTop(*ls),(*p) ))
        {        
            Pop(ls,x);            
        }
         else
        {
            Push(ls,*p);
        }        
            p++;    
    }
     return EmptyStack(*ls);
}



int main( int argc,  char* argv[])
{

    LStackTp *S;
    InitStack(&S);

     char *p= " (()){}[]{{}({})}({[()]}) ";

     if (Matcher(&S,p))
        printf( " 这是一个合法的括号序列! ");
     else
        printf( " 这是一个不合法的括号序列! ");


    printf( " \n\n\n\n\n ");
     return  0;

} 

转载于:https://www.cnblogs.com/lance2088/archive/2011/09/27/2192726.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值