说明
- 本程序需要你将待检测的内容保存在一个文件中,然后在程序运行时,输入那个文件的文件名
源代码
#include <stdio.h>
#include <stdlib.h>
typedef struct NODE{
char data;
struct NODE *next;
struct NODE *pre;
}Node;
#define size sizeof(struct NODE)
Node *init_stack(){
Node *head = (Node *)malloc(size);
head->pre = NULL;
head->next = NULL;
return head;
}
Node *push_stack(Node *top,char x){
if(top->next == NULL){
Node *newNode = (Node *)malloc(size);
newNode->data = x;
top->next = newNode;
newNode->pre = top;
newNode->next = NULL;
}else{
top->next->data = x;
}
return top->next;
}
Node *pop_stack(Node *top){
if(top->pre == NULL){
printf("链为空!\n");
exit(-1);
}
Node *preNode = top->pre;
preNode->next = NULL;
free(top);
return preNode;
}
void match(char *fileName){
Node *head = init_stack();
Node *top = head;
int flag = 0;
char ch;
FILE *fp;
if((fp = fopen(fileName,"r")) == NULL){
printf("文件打开失败!\n");
exit(-1);
}
while(!feof(fp) && flag == 0){
ch = fgetc(fp);
switch(ch){
case '(':
case '[':
case '{':
case '<':
top = push_stack(top , ch);
break;
case ')':
if(top->data == '('){
top = pop_stack(top);
}else{
flag = 1;
}
break;
case ']':
if(top->data == '['){
top = pop_stack(top);
}else{
flag = 1;
}
break;
case '}':
if(top->data == '{'){
top = pop_stack(top);
}else{
flag = 1;
}
break;
case '>':
if(top->data == '<'){
top = pop_stack(top);
}else{
flag = 1;
}
break;
}
}
if(flag == 1 || top->pre != NULL){
printf("至少有一处括号不匹配!\n");
}else{
printf("括号全部匹配.\n");
}
}
int main() {
char fileName[100];
printf("请输入要判断的文件路径:\n");
gets(fileName);
match(fileName);
return 0;
}