Description
试按表头、表尾的分析方法编写求广义表的深度的递归程序。
Input
输入一串以‘(’开始,以‘(’结束的字符串,并且输入的左右括号必须匹配,如:(),(())……
Output
分别输出按表头、表尾分析方法求广义表深度的结果,每个结果占一行。
- Sample Input
((a,b,(c,(d,e),f)),g)
- Sample Output
4 4
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef char ElemType;
typedef struct lnode
{
int tag;
union
{
ElemType data;
struct lnode *sublist;
} val;
struct lnode *link;
} GLNode;
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
{
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;
}
int GLDepth(GLNode *g)
{
GLNode *g1;
int maxg=0,dep;
if (g->tag==0)
return 0;
g1=g->val.sublist;
if (g1==NULL)
return 1;
while (g1!=NULL)
{
if (g1->tag==1)
{
dep=GLDepth(g1);
if (dep>maxg)
maxg=dep;
}
g1=g1->link;
}
return(maxg+1);
}
int main()
{
char s[10005];
gets(s);
char *str=s;
GLNode *q;
q=CreateGL(str);
int depth;
depth=GLDepth(q);
printf("%d\n%d",depth,depth);
return 0;
}
typedef enum {ATOM,LIST} ElemTag;
typedef struct GLNode{
ElemTag tag;
union {
char atom;
struct {
GLNode *hp, *tp;
} ptr;
}un;
} *GList;
int GListDepth(GList ls)
/* Return the depth of list */
{
int max = 0,dep = 0;
GList p;
if(!ls) return 1;//空表深度为1
if(ls -> tag == ATOM)return 0;//原子深度为0
for(max = 0,p = ls; p; p = p -> un.ptr.tp){
dep = GListDepth(p -> un.ptr.hp);//求以p->un.ptr.hp为头结点的子表深度
if(dep > max)
max = dep;
}
return max + 1;//非空表的深度是各元素的深度的最大值加1
}