括号匹配的原理:
程序实现:
头文件:
c3-1.h
#ifndef C_3_1_H
#define C_3_1_H
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define TRUE 1
#define FALSE 0
#endif
algorithm.h
//头文件里面最好只放声明类的文件
#ifndef ALGORITHM_H
#define ALGORITHM_H
#include "c3-1.h"
#define STACK_INIT_SIZE 10
#define STACKINCREMENT 2
//这样做会提高程序的扩展性
typedef char ElementType;
struct node
{
ElementType data;
struct node *pNext; //这个指针需要指向下一个结点
};
typedef struct node NODE;
typedef struct node *PNODE;
struct StackRecord
{
PNODE base;
PNODE top;
};
typedef struct StackRecord Stack;
typedef struct StackRecord *PStack;
int InitStack(PStack s);
int StackEmpty(PStack s);
int DestroyStack(PStack s);
int ClearStack(PStack s);
void Push(PStack s, ElementType value);
int Pop(PStack s, ElementType *e);
#endif
栈操作函数:
#include "algorithm.h"
#include "c3-1.h"
//初始化一个链表栈
int InitStack(PStack s)
{
s->top = (NODE *)malloc(sizeof(NODE));
if (NULL == s->top)
{
printf("Error!\n");
return FALSE;
}
else
{
s->base = s->top;
s->top->pNext = NULL;
return TRUE;
}
}
int DestroyStack(PStack s)
{
free(s->base);
s->base = NULL;
free(s->top);
s->top = NULL;
return TRUE;
}
int ClearStack(PStack s)
{
s->top = s->base;
return TRUE;
}
void Push(PStack s, ElementType value)
{
PNODE pNew = (NODE *)malloc(sizeof(NODE));
pNew->data = value;
pNew->pNext = s->top;
s->top = pNew;
}
int StackEmpty(PStack s)
{
return s->top==s->base;
}
int Pop(PStack s, ElementType *e)
{
if (StackEmpty(s))
{
printf("栈为空,出栈失败!\n");
return FALSE;
}
else
{
PNODE p = s->top;
*e = p->data;
s->top = p->pNext;
free(p);
p = NULL;
return TRUE;
}
}
测试主函数
/*
对于输入的任意一个字符串,检验括号是否匹配
检验括号是否匹配的方法可用“期待的急迫程度”这个概念来描述
*/
#include "algorithm.h"
#include "c3-1.h"
void check(void);
int main(void)
{
check();
}
//括号匹配检查函数
void check(void)
{
Stack s;
char ch[80];
char *p = NULL;
char e = 0;
if (InitStack(&s))
{
printf("请输入表达式:\n");
/*gets()函数读取换行符之前(不包括换行符)的所有字符,
在这些字符后面添加一个空字符(\0),然后把这个字符串交给调用它的程序
空字符的值为0
*/
gets(ch);
p = ch;
while(*p)
{
switch(*p)
{
//如果是左括号则入栈
case '(': Push(&s, *p++);
break;
case '[': Push(&s, *p++);
break;
case ')':
case ']':
if (!StackEmpty(&s)) //栈不空
{
//弹出栈顶元素
Pop(&s, &e);
//弹出的栈顶元素与*p不配对
if ((*p==')'&&e!='(') || ( *p==']'&&e!='['))
{
printf("左右括号不配对\n");
exit(-1);
}
//括号匹配
else
{
p++; //指针后移
break; //跳出switch语句
}
}
else //栈空
{
printf("缺乏左括号!\n");
exit(-1);
}
default: p++; //其他字符不处理,指针向后移
}
}
}
}