使用堆栈可以实现对括号的匹配检查,比如输入{[]}会告诉你输入正确,当输入[(])的时候就会报错
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define SIZE_OF_STACK 30
#define SIZE_NEW_STACK 5
#define true 1
#define false 0
typedef struct bracket
{
char *base;
char *top;
int sizeOfStack;
} BRACKET;
int initStack(BRACKET *myBracket);
int destoryStack(BRACKET *myBracket);
int push(BRACKET *myBracket, char temp);
int getTop(BRACKET *myBracket, char *temp);
int visitStack(BRACKET tempStack);
int isEmptyStack(BRACKET tempStack);
int main()
{
char templeft, tempright, templeft0;
int flag = 0;
BRACKET myBracket;
while(true)
{
while(true)
{
flag = 0;
initStack(&myBracket);
printf("please input a string:\n");
scanf("%c", &templeft);
while(templeft != '\n' && (templeft == ']' || templeft == '}' || templeft == ')' ||
templeft == '(' || templeft == '{' || templeft == '['))
{
templeft0 = templeft;
switch(templeft)
{
case '{':
case '[':
case '(':
push(&myBracket, templeft);
break;
case '}':
getTop(&myBracket, &tempright);
if(tempright != '{')
{
printf("{和}括号不匹配!\n");
flag = 1;
}
break;
case ']':
getTop(&myBracket, &tempright);
if(tempright != '[')
{
printf("[和]括号不匹配!\n");
flag = 1;
}
break;
case ')':
getTop(&myBracket, &tempright);
if(tempright != '(')
{
printf("(和)括号不匹配! \n");
flag = 1;
}
break;
}
scanf("%c", &templeft);
}
//visitStack(myBracket);
if(templeft0 != ']' && templeft0 != '}' && templeft0 != ')' &&
templeft0 != '(' && templeft0 != '{' && templeft0 != '[')
{
printf("输入不合法!\n");
break;
}
else
{
if(isEmptyStack(myBracket) && flag != 1)
{
printf("完全正确!\n");
}
else if(flag != 1)
{
printf("你漏选了一些括号!\n");
}
}
}
}
return 0;
}
int initStack(BRACKET *myBracket)
{
myBracket->base = (char *)malloc(SIZE_OF_STACK * sizeof(char));
if(myBracket->base == NULL)
{
printf("fail to get memory");
exit(1);
}
myBracket->top = myBracket->base;
myBracket->sizeOfStack = SIZE_OF_STACK;
return true;
}
int destoryStack(BRACKET *myBracket)
{
free(myBracket->base);
myBracket->base = NULL;
myBracket->top = NULL;
myBracket->sizeOfStack = 0;
return true;
}
int push(BRACKET *myBracket, char temp)
{
if(myBracket->top - myBracket->base >= SIZE_OF_STACK)
{
myBracket->base = (char *) realloc(myBracket->base, sizeof(char) * SIZE_NEW_STACK);
if(myBracket->base == NULL)
{
printf("fail to get memory");
exit(1);
}
myBracket->top = myBracket->base + SIZE_OF_STACK;
myBracket->sizeOfStack += SIZE_OF_STACK;
}
*myBracket->top++ = temp;
return true;
}
int getTop(BRACKET *myBracket, char *temp)
{
if(myBracket->top == myBracket->base)
{
printf("no information\n");
return false;
}
*temp = *(--myBracket->top);
return true;
}
int visitStack(BRACKET tempStack)
{
if(tempStack.base == tempStack.top)
{
printf("have no information!\n");
return false;
}
while(tempStack.base < tempStack.top)
{
printf("%c", *(--tempStack.top));
}
printf("\n");
return true;
}
int isEmptyStack(BRACKET tempStack)
{
if(tempStack.base == tempStack.top)
return true;
return false;
}