括号匹配

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<windows.h>

typedef struct Node{
char data;
struct Node *pNext;
}NODE,*PNODE;  //构造节点 

typedef struct Stack{
PNODE pTop;
PNODE pBottom;
}STACK,*PSTACK; //构造堆栈,pTop永远指向栈顶,pBottom指向栈底 
//pBottom指向最后一个有效元素的下一个元素,便于链表操作 

/*函数声明*/ 
void initStack(PSTACK);//初始化栈 
void push(PSTACK,char);//压栈 
bool pop(PSTACK,char*);//出栈 
void traverse(PSTACK);//遍历 
bool isEmpty(PSTACK);//判断堆栈是否为空 
bool match(PSTACK,char);//匹配 

int main()
{   STACK S;//等价于struct Stack S; 
    initStack(&S);//初始化哟! 
char sign[100],*n,val;
int i=0;
n=sign;
printf("请输入形如[]{}()的表达式,我们将进行匹配:");
gets(sign);
    /*while(*n)
{
push(&S,*n);
*n++; 
}
traverse(&S);*/
    while(*n)
{
 switch(*n)
{
case '{':
case '[':
   case '(':push(&S,*n++);i++;break;//左边括号就入栈 
   case '}':
   case ']':
   case ')':
        if(match(&S,*n++))
       {
       printf("第%d个符号匹配成功!\n",i);
       i++;
       }else{
       printf("第%d个符号匹配失败或堆栈为空!\n",i);
       i++;
       }//右边括号就匹配 
       break;
   default:*n++;i++;//输入错误的符号,默认跳过 
}
    }
    system("pause");
return 0;
}

void initStack(PSTACK pS)
{
   pS->pTop=(PNODE)malloc(sizeof(NODE));//初始化时pTop和pBottom都指向一个节点 
   if(NULL==pS->pTop)
   {
   printf("error!");
   exit(-1);
   }else{
   pS->pBottom=pS->pTop;
   pS->pTop->pNext=NULL;//将底层节点的下个节点置空 
   }
}

void push(PSTACK pS,char val) 
{
PNODE pNew=(PNODE)malloc(sizeof(NODE));
if(pNew==NULL)
{
printf("error!");
exit(-1);
}
pNew->data=val;
pNew->pNext=pS->pTop;
pS->pTop=pNew;
} 

bool pop(PSTACK pS,char *pVal)
{
if((isEmpty(pS)))
{
return false;
}else
{
PNODE r=pS->pTop;
*pVal=r->data;
pS->pTop=r->pNext;
free(r);
r=NULL;
return true;
}
} 

bool isEmpty(PSTACK pS)
{
if(pS->pBottom==pS->pTop)
{
 return true;
}
else 
{
 return false;
}
}

void traverse(PSTACK pS)
{
PNODE p=pS->pTop;
while(p!=pS->pBottom)
{
printf("%c",p->data);
p=p->pNext;
}
printf("\n");
return;
}


bool match(PSTACK pS,char n)
{   char temp;
    if(!pop(pS,&temp))
    {
    printf("栈空!");
    return false; 
    }
    /*printf("%c",n);
    printf("%c",temp);*/
if(temp=='['||temp=='('||temp=='{')
    {
    return true;
    }else{
    return false;
    }
}


你可能感兴趣的:(括号匹配)