1.使用函数一览
void DestroyLStack(LinkStNode * s);//销毁链栈
bool EmptyLStack(LinkStNode *s);//判空
bool Push(LinkStNode *s,ElemType e);//入栈操作
bool Pop(LinkStNode *s,ElemType e);//出栈操作
int GetLTop(LinkStNode *s,ElemType e);//取栈顶元素
bool MatchStack(LinkStNode *s,char exp[],int n);//匹配括号函数
2.头文件预编译
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef char ElemType;
3.判空函数
bool EmptyLStack(LinkStNode *s){
if(s -> next == NULL){
printf("链栈为空\n");
return false;
} else{
printf("链栈不为空\n");
return true;
}
}
4.入栈函数
bool Push(LinkStNode *s,ElemType e){
LinkStNode *p;
p = (LinkStNode*) malloc(sizeof(LinkStNode));
p -> data = e;
p -> next = s -> next;
s -> next = p;
printf("%c入栈成功\n",e);
return true;
}
5.出栈函数
bool Pop(LinkStNode *s,ElemType e){
if(s -> next == NULL){
printf("栈为空\n");
return false;
}
LinkStNode *p;
p = s -> next;
e = p -> data;
s -> next = p -> next;
free(p);
printf("%c删除成功\n",e);
return e;
}
6.取栈顶元素函数
int GetLTop(LinkStNode *s,ElemType e){
if(s -> next == NULL){
printf("栈为空\n");
return false;
}
LinkStNode *p;
p = s -> next;
e = p -> data;
printf("栈顶元素是%d\n",e);
return e;
}
7.销毁函数
void DestroyLStack(LinkStNode * s) {
LinkStNode *pre = s,*p = s -> next;
while (p != NULL){
free(pre);
pre = p;
p = pre -> next;
}
free(pre);
printf("销毁成功\n");
}
8.匹配函数
bool MatchStack(LinkStNode *s,char exp[],int n){
int i = 0; char e;
bool match = true;
while (i < n && match){
if(exp[i] == '(') //左括号进栈,右括号判断栈顶元素,匹配则出栈
Push(s,exp[i]);
else if(exp[i] == ')'){
if(EmptyLStack(s) == true)
{
int x = GetLTop(s,e);
if(x != '(')
match = false;
else
Pop(s,e);
}
} else{ //其他情况直接退出
match = false;
}
i++;
}
if(EmptyLStack(s)) //链栈不为空,有括号未能匹配
match = false;
if(match)
printf("匹配成功\n");
else
printf("匹配失败\n");
DestroyLStack(s);
return match;
}
9.主函数
int main(){
LinkStNode *p;
p = (LinkStNode * ) malloc(sizeof(LinkStNode));
p -> next = NULL;
char exp[10] = {'(','(',')',')','(','(','(',')',')',')'};
MatchStack(p,exp,10);
}
对于括号匹配算法,栈的先进后出特性十分实用。