广义表建立及求其深度算法

#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;
}



                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值