使用堆栈实现括号匹配(C言语)
#include <stdio.h>
#include <stdlib.h>
//#include "Anti_2_3_2.h"
//数据域的类型定义
typedef struct
{
int index;
char ch;
}StackData;
typedef StackData StackDataType; //堆栈数据类型;
typedef struct StackNode //堆栈节点定义;
{
StackDataType *data;
struct StackNode *next;
}StackNode,AntiStack,*pStackNode,*pAntiStack;
//初始化堆栈,生成一个头结点
int InitAntiStack_L(AntiStack ** stack)
{
(*stack)=(pAntiStack) malloc (sizeof(StackNode));
if(!(*stack)) return 0;
(*stack)->next=NULL;
return 1;
}
//进栈操作
int Push_L(AntiStack **stack, StackDataType *e)
{
pStackNode node;
pStackNode p;
if(!(node=(pAntiStack)malloc(sizeof(StackNode)))) return 0;
node->data=e;
node->next=(*stack)->next;
(*stack)->next=node;
return 1;
}
int Pop_L(AntiStack **stack, StackDataType **e)
{
pStackNode p;
if(bIsEmpty_L(*stack)) return 0;
p=(*stack)->next;
(*e)=p->data;
(*stack)->next=p->next;
free(p);
return 1;
}
int bIsEmpty_L(AntiStack *stack)
{
if(stack->next==NULL) return 1;
else return 0;
}
int ClearStack_L(AntiStack **stack)
{
(*stack)->next=NULL;
}
/////堆栈设计结束
//判断是否为左括号,如果是,则入栈;
int bPush(char ch)
{
if(ch=='('||ch=='['||ch=='{') return 1;
else return 0;
}
//判断是否是右括号,如果是,则出栈;
int bPop(char ch)
{
if(ch==')'||ch==']'||ch=='}') return 1;
else return 0;
}
//括号匹配,注意;ch1 代表的是左括号的部分,也就是出栈时的符号
int bCompare(char ch1,char ch2)
{
if(ch1=='('&&ch2==')')return 1;
if(ch1=='['&&ch2==']')return 1;
if(ch1=='{'&&ch2=='}')return 1;
return 0;
}
//生成一个堆栈的节点
StackDataType *MakeNode_Stack(char ch,int index)
{
StackDataType *node;
if(!(node=(StackDataType *)malloc(sizeof(StackDataType)))) return NULL;
node->ch=ch;
node->index=index;
return node;
}
int Run_ds_3_2_2()
{
char string[1000]; //数据缓存
char *p; //字符串操作指针;
int flag=0; //状态标志位,为0表示字符串中没有括号
AntiStack *stack; //堆栈,使用链式结构存储数据;
StackDataType *e; //数据节点,这里定义为一个结构类型,标识括号和所在的位置;
InitAntiStack_L(&stack);
while(gets(string)&&string[0]!='\0')
{
p=string;
flag=0;
ClearStack_L(&stack); //每次操作之前,清空栈,以免影响堆栈的正确性;
while(*p!='\0')
{
if(bPush(*p)) //如果是左括号,则入栈;
{
Push_L(&stack,MakeNode_Stack(*p,p-string)); //将左括号和它的位置压入堆栈中
flag=1;
}
if(bPop(*p)) //如果是右括号,则出栈,并进行符号的匹配;
{
if(!Pop_L(&stack,&e)) break;
else if(!bCompare(e->ch,*p)) break;//匹配不成功,直接退出;
}
p++;
}
if(*p!='\0'||!bIsEmpty_L(stack)) printf("ERROR! index:%d\n",p-string+1);
else
{
if(flag==0) printf("there is no brackets in the text!\n");
else printf("OK!\n");
}
}
return 1;
}
int main(int argc, char *argv[])
{
Run_ds_3_2_2();
system("PAUSE");
return 0;
}