1、括号匹配问题
参考书:《数据结构(C语言)》–严蔚敏等编著,清华大学出版社。
顺序栈相关进栈出栈过程:链栈的进栈出栈过程
相关代码:
#include "stdio.h"
#include "stdlib.h"
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef char SElemType;
typedef struct StackNode {
SElemType data; //栈元素
struct StackNode *next; //链栈指针,作为栈的栈顶
} StackNode, *LinkStack;
Status InitStack_S(LinkStack &S);
//构造一个链栈S
Status InitStack_S(LinkStack &S) {
S = NULL; //空链栈
return OK;
}
Status Push_S(LinkStack &S,SElemType e);
//进栈
Status Push_S(LinkStack &S,SElemType e) {
LinkStack p;
p = new StackNode;
p->data = e;
p->next = S;
S = p; //更新头指针的指向
return OK;
}
Status Pop_S(LinkStack &S,SElemType &e);
//出栈,e返回其值
Status Pop_S(LinkStack &S,SElemType &e) {
LinkStack p;
if(S == NULL) return ERROR;
p = new StackNode;
e = S->data; //将栈顶元素data值给e
p = S; //p指向S(顶)
S = S->next; //S下移
free(p); //释放顶节点
return OK;
}
Status StackEmpty_S(LinkStack S);
//判空栈
Status StackEmpty_S(LinkStack S) {
if(S == NULL) return TRUE;
else return FALSE;
}
Status GetTop_S(LinkStack S,SElemType &e);
//获取栈顶元素,e返回其值
Status GetTop_S(LinkStack S,SElemType &e) {
if(S == NULL) return ERROR;
e = S->data;
return OK;
}
Status StackMatch(LinkStack S);
//括号匹配
Status StackMatch(LinkStack S) {
SElemType e,ch;
int flag = 1; //设置标记
while((ch=getchar()) != '#' && flag){
switch(ch) {
case '(':
case '[':
case '{': Push_S(S,ch); break;
case ')': if(Pop_S(S,e)==ERROR || e!='(')
flag = 0;
break;
case ']': if(Pop_S(S,e)==ERROR || e!='[')
flag = 0;
break;
case '}': if(Pop_S(S,e)==ERROR || e!='{')
flag = 0;
break;
}
}
if(StackEmpty_S(S) && flag) return TRUE;
else return FALSE;
}
int main(void) {
LinkStack S;
InitStack_S(S);
if(StackMatch(S))
printf("匹配\n");
else
printf("不匹配\n");
return 0;
}/*
输入:[([([])])]#
输出:匹配
输入:[([()])](#
输出:不匹配
输入:[(]#
输出:不匹配
*/