2024-3-18

This commit is contained in:
2024-03-18 20:18:12 +08:00
parent 8933bff3c7
commit 59e0405033
51 changed files with 5263 additions and 0 deletions

View File

@@ -0,0 +1,69 @@
/***链栈实现括号匹配***/
#include<string>
#include<iostream>
using namespace std;
#include"LinkStack.h"
//算法3.11 括号的匹配
bool match(string exp)
{
//检验表达式(表达式以"#"结束)中所含"["和"]"、"("和")"是否匹配如果匹配则返回true否则返回false。
//表达式以“#”结束
SNode<char> *S;
InitStack(S);
int flag=1; // 标记查找结果以控制循环及返回结果
char ch;
char e,x;
int i=0;
ch=exp[i++]; // 读入第一个字符
while(ch!='#' && flag)
{
switch (ch)
{
case '[':
case '(': // 若是左括号,则将其压入栈
cout<<"左括号进栈!"<<endl;
Push(S,ch);
break;
case ')' : // 若是右括号“)”,则根据栈顶元素的值分情况考虑
GetTop(S,e);
if (!StackEmpty(S) && e=='(' ) // 若栈非空且栈顶元素是“(”,则匹配成功
{
Pop(S,x);
cout<<"右括号出栈!"<<endl;
}
else
flag=0; // 若栈空或栈顶元素不是“(”,则非法
break;
case ']' : // 若是右括号“]”,则根据栈顶元素的值分情况考虑
GetTop(S,e);
if (!StackEmpty(S) && e=='[' ) // 若栈顶元素是“[”,则匹配成功
Pop(S,x);
else
flag=0; // 若栈空或栈顶元素不是“[”,则非法
break;
}//switch
ch=exp[i++]; //继续读入下一个字符
}//while
if (StackEmpty(S) && flag ) // 栈空且标志为true,括号匹配返回true
return true;
else // 否则,括号不匹配,返回false
return false;
}//match
int main()
{
int flag;
string exp;
cout<<"请输入待匹配的表达式,以“#”结束:"<<endl;
cin>>exp;
flag = match(exp);
if(flag)
cout<<"括号匹配成功!"<<endl;
else
cout<<"括号匹配失败!"<<endl;
return 0;
}//end of main function

View File

@@ -0,0 +1,92 @@
template <class DT>
struct SNode //结点
{
DT data; //数据域,存储数据元素值
SNode *next;//指针域,指向下一个结点
};
//【算法3.6】
template <class DT>
void InitStack(SNode<DT> *&S)//创建空链栈
{
S=NULL;
}
//【算法3.7】
template <class DT>
void DestroyStack(SNode<DT> *(&S))//释放链栈
{
SNode<DT> *p;
while(S)//从头结点开始,依次释放结点
{
p=S;
S=S->next;
delete p;
}
//L=NULL;//头结点指向空
}
//【算法3.8】
template<class DT>
bool Push(SNode<DT> *&S,DT e)
{
SNode<DT> *p;
p=new SNode<DT>;
if(!p) return false; //创建失败,结束运行
p->data=e; // 新结点赋值
p->next=S; //结点S链接到p结点之后
S=p;
return true; // 插入成功返回true
}
//【算法3.9】
template<class DT>
bool Pop(SNode<DT> *&S,DT &e)
{
SNode<DT> *p;
if(S==NULL) return false;
p=S;
e=p->data;
S=S->next;
delete p;
return true; // 删除成功返回true
}
//【算法3.10】
template<class DT>
bool GetTop(SNode<DT> *S,DT &e)
{
SNode<DT> *p;
if(S==NULL) return false;
p=S;
e=p->data;
return true; // 删除成功返回true
}
//测栈空
template<class DT>
bool StackEmpty(SNode<DT> *S)
{
if(S==NULL)
return true;
else
return false;
}
//显示栈内容
template<class DT>
void DispStack(SNode<DT> *S)
{
SNode<DT> *p;
p=S;
while(p)
{
cout<<p->data<<"\t";
p=p->next;
}
cout<<endl;
}