#include<stdio.h>
#include<stdlib.h>
#include <malloc.h>
#define MAX 1001
//此程序采用顺序栈做法
typedef char ElementType;
//新建一个栈结构
typedef struct stack{
ElementType a;
struct stack *next;
} List,*lp;
//初始化栈
struct stack *create();
int Push(lp L,ElementType x);//入栈
int Pop(lp L,ElementType e);//出栈
int main(){
char s[MAX];//新建一个数组并存储输入的代码
gets(s);
int i=0,left=0,right=0,flag=1 ;
lp L=NULL;//新建一个栈指针,并初始化
L=create();
while(s[i]!='\0'){
if(s[i]=='('){
Push(L,'(');
left++;
} else if(s[i]=='['){
Push(L,'[');
left++;
} else if(s[i]=='{') {
Push(L,'{');
left++;
} else if(s[i]==')'){
if(Pop(L,'(')!=1)flag=0;
right++;
//printf("%d",flag);
}else if(s[i]==']') {
if(Pop(L,'[')!=1) flag=0 ;
right++;
//printf("%d",flag);
} else if(s[i]=='}') {
if(Pop(L,'{')!=1) flag=0 ;
right++;
//printf("%d",flag);
}
i++;
}
if(L->next!=NULL) {flag=0;
}
printf("%d %d\n",left,right);
if(flag==1){
printf("YES\n");
}else{
printf("NO\n");
}
}
struct stack *create(){
lp s=NULL;//新建一个栈指针
s=(lp)malloc(sizeof(lp));
s->next=NULL;
return s;
}
int Push(lp L,ElementType x){
lp p=(lp)malloc(sizeof(lp));
p->a=x;
p->next=L->next;
L->next=p;
return 1;
}
int Pop(lp L,ElementType e){
lp p=(lp)malloc(sizeof(lp));
if(L->next==NULL) return 0;
p=L->next;
if(p->a==e){
L->next=p->next;
free(p);
return 1;
}else{
return 0;
}
}
数据结构 括号匹配(C语言)
最新推荐文章于 2024-04-01 02:05:22 发布