判断一行字符串输入"各种括号"是否是合法的-----------------------栈用数组实现
如:[()]是合法的(balance)
[(])是不合法的(imbalance)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Node
{
int Capacity;
int TopOfStack;
char *Array;
};
typedef struct Node *Stack;
//创建栈
Stack CreatStack(int MaxElem)
{
Stack S;
S = malloc(sizeof(struct Node));
if(S == NULL)
{
printf("创建失败");
exit(0);
}
S->Array=malloc(MaxElem*sizeof(char));
if(S->Array==NULL)
printf("创建失败");
S->Capacity=MaxElem;
S->TopOfStack=-1;
return S;
}
int IsEmpty(Stack S)
{
return S->TopOfStack == -1;
}
int IsFull(Stack S)
{
return S->TopOfStack == S->Capacity - 1;
}
void Push(char x,Stack S)
{
if(IsFull(S))
printf("栈满");
else
S->Array[++S->TopOfStack] = x;
}
void Pop(Stack S)
{
if(IsEmpty(S))
printf("栈空");
else
S->TopOfStack--;
}
char Top(Stack S)
{
if(IsEmpty(S))
printf("栈空");
else
return S->Array[S->TopOfStack];
}
int main()
{
char str[100];
scanf("%s", str);
int len = strlen(str);
Stack S = CreatStack(len + 1);
for (int i = 0; i < len; i++)
{
if(str[i]=='('||str[i]=='['||str[i]=='{')
Push(str[i], S);
else if (str[i]==')'&&Top(S)=='(')
Pop(S);
else if (str[i]==']'&&Top(S)=='[')
Pop(S);
else if (str[i]=='}'&&Top(S)=='{')
Pop(S);
}
if(IsEmpty(S))
printf("符号匹配");
else
printf("符号不匹配");
}
样例
{[]}
符号匹配
[(])
符号不匹配
([{}])
符号匹配