//---------------------------kuohao.c------------------------------
/*
使用方法
gcc kuohao.c -o kuohao
./kuohao name name待检测的文件
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
typedef char Elemtype;
#define StackMaxSize 100
struct Stack
{
Elemtype stack[StackMaxSize];
int top;
};
static void init_stack(struct Stack * H)
{
H=(struct Stack *) malloc (sizeof(struct Stack));
if(H==NULL)
{
printf("malloc error/n");
exit(-1);
}
}
static void push_stack(struct Stack *H, Elemtype item)
{
if(H->top==StackMaxSize-1)
{
printf("Stack fully/n");
exit(-1);
}
H->top++;
H->stack[H->top]=item;
}
static Elemtype pop_stack(struct Stack *H)
{
Elemtype e;
if((H->top)<0)
{
printf("又括号太多/n");
return -1;
}
e=H->stack[H->top];
H->top--;
return e;
}
//上面代码是用于实现栈的代码
int main(int argc, char *argv[])
{
if(argc!=2)
{
printf("请输入命令名和文件明/n");
exit(-1);
}
FILE *fp;
char ch;
struct Stack *S;
init_stack(S);
S->top=-1;
fp=fopen(argv[1],"r");
while((ch=getc(fp))!=EOF)
{
if(ch=='(' | ch=='{' | ch=='[' | ch=='<')
{
push_stack(S,ch);
}
else if(ch==')' | ch=='}' | ch==']' | ch=='>')
{//如果是右括号,那就出栈比较吧
switch(ch)
{
case ')':
if(pop_stack(S)!='(')
{
printf("匹配错误/n");
exit(-1);
}
break;
case '}':
if(pop_stack(S)!='{')
{
printf("匹配错误/n");
exit(-1);
}
break;
case ']':
if(pop_stack(S)!='[')
{
printf("匹配错误/n");
exit(-1);
}
break;
case '>':
if(pop_stack(S)!='<')
{
printf("匹配错误/n");
exit(-1);
}
break;
}
}
else//如果是空格,字符之类,则什么也不做
{
}
}
if(S->top!=-1)
{
printf("左括号太多/n");
exit(-1);
}
printf("完全匹配^_^/n");
exit(0);
}
栈应用--括号匹配检测
最新推荐文章于 2017-01-15 18:42:09 发布