//头文件
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define MaxSize 20
typedef char ElemType;
typedef int Status;
//链栈结点数据结构
typedef struct StackNode
{
ElemType data;//数据域
struct StackNode *next;//指针域
}StackNode, *LinkStack;
//初始化函数
Status InitStack(LinkStack *S)
{
(*S) = NULL;//生成空栈 以单链表表头为栈顶 注意,链栈没有像链表似的头结点
return OK;
}
//入栈函数 将e压入栈
Status Push(LinkStack *S, ElemType e)
{
StackNode *p;
p = (LinkStack)malloc(sizeof(StackNode));
p->data = e; //赋值
p->next = (*S); //压入栈顶
(*S) = p;
return OK;
}
//出栈函数 栈顶出栈用e返回 注意释放空间
char Pop(LinkStack *S)
{
LinkStack p;
if (S == NULL) return ERROR;//栈空
char e = (*S)->data;
p = (*S);
(*S) = (*S)->next;
free(p);
return e;
}
//取栈顶函数 用e返回
Status GetTop(LinkStack S, ElemType *e)
{
if (S == NULL) return ERROR;//栈顶为空
(*e) = S->data;
return OK;
}
//判空
Status isEmpty(LinkStack S)
{
if (NULL == S)
{
return TRUE;
}
return FALSE;
}
int getlength(LinkStack S) //取栈的地址,进行查看栈的长度
{
LinkStack p = S;
int length = 0;
while (p->next != NULL)
{
p = p->next;
length++;
}
return length;
}
//清空栈的空间 这只是销毁栈的存储数据的空间,没有销毁栈首的位置
void clearstack(LinkStack *S)
{
while (!isEmpty(*S))
{
Pop(S);
}
}
//销毁栈空间
void destorystack(LinkStack *S)
{
while (!isEmpty((*S)))
{
Pop(S);
}
free(S);
S = NULL;
}
//主程序
#include "Lab3_1_Stack.h"
#include <string.h>
Status check(LinkStack stack, char s[])
{
char ch;
for(int i=0;i<strlen(s);i++)//遍历字符串
{
if(s[i]=='('||s[i]=='{'||s[i]=='[')//如果是左括号
{
Push(&stack, s[i]);//直接入栈
}
else//如果右括号
{
GetTop(stack, &ch);
if (isEmpty(stack))//如果栈空了字符串还没遍历完说明右括号比左括号多
{
printf("括号匹配失败:右括号比左括号多!");
return FALSE;
}
if(s[i]==')')//检查()匹配
{
if (ch == '(')
{
Pop(&stack);
continue;
}
else
{
printf("括号匹配失败:括号次序错误!");
return FALSE;
}
}
else if (s[i] == ']')//检查[]匹配
{
if (ch == '[')
{
Pop(&stack);//出栈
continue;
}
else
{
printf("括号匹配失败:括号次序错误!");
return FALSE;
}
}
else//检查{}匹配
{
if (ch == '{')
{
Pop(&stack);//出栈
continue;
}
else
{
printf("括号匹配失败:括号次序错误!");
return FALSE;
}
}
}
}
if (!isEmpty(stack))
{
printf("括号匹配失败:左括号比右括号多!");
return FALSE;
}
printf("括号匹配正确!");
return OK;
}
int main()
{
char str[MaxSize];
LinkStack stack;
InitStack(&stack);//初始化
scanf("%s", &str);
check(stack, str);//检查匹配
}