#include<iostream>
#include<stdlib.h>
using namespace std;
typedef char ElemType;
typedef struct lnode
{
int tag;//结点类型标识
union
{
ElemType data;//存放原子值
struct lnode *sublist;//指向子表的指针
}val;
struct lnode *link;//指向下一个元素
}GLNode; //广义表的结点类型
int GLLength(GLNode *g)//求长度
{
int n=0;
GLNode *gl;
gl=g->val.sublist;
while(gl!=NULL)
{
n++;
gl=gl->link;
}
return n;
}
int GLDepth(GLNode *g)//求深度
{
GLNode *gl;
int maxd=0,dep;
if(g->tag==0)
return 0;
gl=g->val.sublist;
if(gl==NULL)
return 1;
while(gl!=NULL)
{
if(gl->tag==1)
{
dep=GLDepth(gl);
if(dep>maxd)
maxd=dep;
}
gl=gl->link;
}
return(maxd+1);
}
GLNode *CreateGL(char *&s)//链式存储
{
GLNode *g;
char ch=*s++;
if(ch!='\0')
{
g=(GLNode *)malloc(sizeof(GLNode));
if(ch=='(')
{
g->tag=1;
g->val.sublist=CreateGL(s);
}
else if(ch==')')
g=NULL;
else if(ch=='#')
g=NULL;
else
{
g->tag=0;
g->val.data=ch;
}
}
else
g=NULL;
ch=*s++;
if(g!=NULL)
if(ch==',')
g->link=CreateGL(s);
else
g->link=NULL;
return g;
}
ElemType MaxAtom(GLNode *g) //求广义表g中最大的原子
{
ElemType m=0,m1; //m赋初值0
while (g!=NULL)
{
if (g->tag==1) //子表的情况
{
m1=MaxAtom(g->val.sublist); //对子表递归调用
if (m1>m) m=m1;
}
else
{
if (g->val.data>m) //为原子时,进行原子比较
m=g->val.data;
}
g=g->link;
}
return m;
}
int main()
{
GLNode *g;
char *str="(b,(b,a,(#),d),((a,b),c((#))))";
cout<<"(1)建立广义表g=(b,(b,a,(#),d),((a,b),c((#))))"<<endl;
g=CreateGL(str);
cout<<"(2)输出广义表g的长度"<<endl;
cout<<GLLength(g)<<endl;
cout<<"(3)输出广义表g的深度"<<endl;
cout<<GLDepth(g)<<endl;
cout<<"(4)输出广义表g的最大原子"<<endl;
cout<<MaxAtom(g)<<endl;
}
广义表
最新推荐文章于 2022-10-19 07:22:19 发布