用栈实现括号匹配–C语言
#include <stdio.h>
#include <stdlib.h>
#include<stdbool.h>
#define MaxSize 10
typedef struct
{
int data[MaxSize];
int top;
} Stack,*SqStack ;
Stack *init_stack(SqStack s)
{
s=(Stack*)malloc(sizeof(Stack));
s->top=-1;
printf("初始化完成!\n");
return s;
}
Stack * push(SqStack s,int x)
{
if(s->top==MaxSize-1)
{
printf("栈满!!\n");
return s;
}
else
{
s->top=s->top+1;
s->data[s->top]=x;
return s;
}
}
int pop(SqStack s,int x)
{
if(s->top==-1)
{
printf("栈空!!\n");
return NULL;
}
else
{
x=s->data[s->top];
s->top=s->top-1;
printf("出栈成功 取出元素为:%c\n",x);
return x;
}
}
int get_top(SqStack s,int x)
{
if(s->top==-1)
{
printf("栈空!!\n");
return NULL;
}
else
{
x=s->data[s->top];
printf("取出成功 取出元素为:%s\n",x);
return x;
}
}
bool empty_stack(SqStack s)
{
if(s->top==-1)
{
return true;
}
else
{
return false;
}
}
bool check(char str[],int length)
{
char temp;
SqStack s;
s= init_stack(s);
for(int i=0; i<length; i++)
{
if(str[i]=='[' || str[i]=='{' || str[i]=='(')
{
printf("扫描到左括号%c\n",str[i]);
s= push(s,str[i]);
}
else
{
if(empty_stack(s))
{
return false;
}
else
{
temp= pop(s,temp);
if(str[i]==')' && temp!='(')
{
return false;
}
else if(str[i]=='}' && temp!='{')
{
return false;
}
else if(str[i]==']' && temp != '[')
{
return false;
}
}
}
}
return empty_stack(s);
}
int main()
{
char str[10]= {'[','(','(','{','[',']','}',')',')',']'};
if( check(str,10))
{
printf("匹配成功!\n");
}
else
{
printf("匹配失败!\n");
}
return 0;
}
运行结果