利用栈,实现括号匹配功能,例:"()"匹配成功,"([]"匹配失败
一、主函数
#include "match.h"
int main(int argc, const char *argv[])
{
S_p S=create_stack();
int count_1,count_2;
//括号入栈
count_1=push_stack(S,'}');
count_1=push_stack(S,']');
count_1=push_stack(S,')');
printf("栈中已存在括号有:\n");
pop_stack(S,count_1);
//输入判断匹配性的括号
char brackets;
for(int i=0;i<count_1+1;i++)
{
printf("请输入括号:\n");
scanf(" %c",&brackets);
count_2=push_stack(S,brackets);
}
pop_stack(S,count_2);
//判断括号是否匹配并出栈
judge_stack(S,count_2);
return 0;
}
二、功能函数
#include "match.h"
//1、创建栈空间
S_p create_stack()
{
S_p S=(S_p)malloc(sizeof(stack));
if(S==NULL)
{
printf("申请空间失败\n");
return NULL;
}
bzero(S,sizeof(stack));
S->top=-1;
return S;
}
//2、判空
int empty_stack(S_p S)
{
if(S==NULL) {return -1;}
return S->top==-1;
}
//3、判满
int full_stack(S_p S)
{
if(S==NULL) {return -1;}
return S->top==MAX-1;
}
//4、入栈
int push_stack(S_p S,char value)
{
if(S==NULL) {return -1;}
if(full_stack(S))
{
printf("元素已满,无法存储\n");
return -2;
}
S->top++;
S->data[S->top]=value;
return S->top;
}
//5、判断括号的匹配性
void judge_stack(S_p S,int count)
{
if(S==NULL) { return ;}
if(empty_stack(S))
{
printf("元素为空,无需判断\n");
return ;
}
if(count%2==0)
{
printf("括号匹配失败\n");
return ;
}
int count_1=count,flag=0;
for(int i=0;i<count_1;i++,count_1--)
{
switch(S->data[i]-S->data[count_1])
{
case 1:
flag=1;
break;
case 2:
flag=1;
break;
default:
printf("括号匹配失败\n");
pop_stack(S,count);
return ;
break;
}
}
if(flag==1)
{
printf("括号匹配成功\n");
pop_stack(S,count);
}
return ;
}
//6、输出栈中元素
void pop_stack(S_p S,int count)
{
if(S==NULL) { return ;}
if(empty_stack(S))
{
printf("元素为空,无需输出\n");
return ;
}
for(int i=count;i>=0;i--)
{
printf("%c ",S->data[i]);
}
printf("\n");
return ;
}
三、头文件
#ifndef __MATCH_H__
#define __MATCH_H__
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 10
typedef struct stack
{
int data[MAX];
int top;
} stack , *S_p;
S_p create_stack();
int empty_stack(S_p S);
int full_stack(S_p S);
int push_stack(S_p S,char value);
void judge_stack(S_p S,int count);
void pop_stack(S_p S,int count);
#endif
运行结果如下:
