输入左括号如'(','['则进栈 右括号如')',']'则从栈里取出一个括号 看着两个括号是否匹配
#include<stdio.h>
#include<stdlib.h>
#define SIZE 6
//define the struct of stack
typedef struct stack
{
char* element;
int top;
int size;
}Stack;
//initialize stack
Stack* initStack(Stack* tempPtr)
{
tempPtr=(Stack*)malloc(sizeof(Stack));
tempPtr->element=(char*)malloc(sizeof(char)*SIZE);
tempPtr->top=0;
tempPtr->size=SIZE;
return tempPtr;
}//Of initStack
//print the stack
void print(Stack* tempPtr)
{
int i;
printf("Stack :");
for(i=0;i<tempPtr->top;i++)
{
printf("%c ",tempPtr->element[i]);
}//Of for i
printf("\n");
}
//push an element into the stack
Stack* push(Stack* tempPtr,char newElement)
{
if(tempPtr->top>=SIZE)
{
printf("Failed! Overflow\n");
return tempPtr;
}//Of if
printf("pushing %c\n",newElement);
tempPtr->element[tempPtr->top]=newElement;
tempPtr->top++;
print(tempPtr);
return tempPtr;
}//Of push
//get an element from the stack
char pop(Stack* tempPtr)
{
if(tempPtr->top==0)
{
printf("NO more element!\n");
}//Of if
tempPtr->top--;
return tempPtr->element[tempPtr->top];
}//Of pop
//match char
void match(Stack* tempPtr,char* str,int length)
{
int i;
char tempChar;
for(i=0;i<length;i++)
{
tempChar=str[i];
switch(tempChar)
{
case '(':
push(tempPtr,tempChar);
break;
case '[':
push(tempPtr,tempChar);
break;
case ')':
printf("matching )\n");
if(tempPtr->top==0)
{
printf("NO more element to match!\n");
break;
}//Of if
if(pop(tempPtr)=='(')
{
printf("( )match scuessful!\n");
print(tempPtr);
}//Of if
else
{
printf("match failed!\n");
print(tempPtr);
}//Of else
break;
case ']':
printf("matching ]\n");
if(tempPtr->top==0)
{
printf("NO more element to match!\n");
break;
}//Of if
if(pop(tempPtr)=='[')
{
printf("[ ]match scuessful!\n");
}//Of if
else
{
printf("match failed!\n");
}//Of else
break;
default:
break;
}//Of switch
}//Of for i
printf("Finished!\n");
}//Of match
void main()
{
Stack* st;
char arr[]="[()]([)]";
st=initStack(st);
/*push(st,'a');
push(st,'b');
push(st,'c');
push(st,'d');
push(st,'e');
push(st,'f');
push(st,'g');
print(st);*/
match(st,arr,8);
}//Of main