#include <iostream>
#include <string>
using namespace std;
typedef enum {ATOM,LIST}ElemTag;
typedef struct GLNode
{
ElemTag tag;
union
{
char atom;
struct
{
struct GLNode* hp,*tp;
}ptr;
};
}*GList;
int GListDepth(GList L)
{
if(L==NULL)
return 1;
if(L->tag==ATOM)
return 0;
int max=0,dep;
for(GList pp=L;pp;pp=pp->ptr.tp)
{
dep=GListDepth(pp->ptr.hp);
if(dep>max)
max=dep;
}
return max+1;
}
void Sever(string& tail,string& head)
{
char ch;
int n=tail.length(),i=0,k=0;
do
{
++i;
ch=tail.substr(i-1,1).at(0);
if(ch=='(') ++k;
else if(ch==')') --k;
}while(i<n&&(ch!=','||k!=0));
if(i<n)
{
head=tail.substr(0,i-1);
tail=tail.substr(i);
}
else
{
head=tail;
tail="";
}
}
GList CreatGList(string s)
{
GList L;
if(s=="()")
return NULL;
else
{
L=new GLNode();
if(s.length()==1)
{
L->tag=ATOM;
L->atom=s[0];
return L;
}
else
{
L->tag=LIST;
GList p=L,q;
string head;
s=s.substr(1,s.length()-2);
do
{
Sever(s,head);
p->ptr.hp=CreatGList(head);
q=p;
if(s.length()!=0)
{
p=new GLNode();
p->tag=LIST;
q->ptr.tp=p;
}
}while(s.length()!=0);
q->ptr.tp=NULL;
}
}
return L;
}
int main()
{
cout<<"请输入广义表:"<<endl;
string s;
cin>>s;
GList L=CreatGList(s);
cout<<"该广义表的深度为:"<< GListDepth(L)<<endl;
return 0;
}
广义表建立及求其深度算法
最新推荐文章于 2022-10-23 18:22:41 发布