Description
试按表头、表尾的分析方法编写求广义表的深度的递归程序。
Input
输入一串以‘(’开始,以‘(’结束的字符串,并且输入的左右括号必须匹配,如:(),(())……
Output
分别输出按表头、表尾分析方法求广义表深度的结果,每个结果占一行。
-
Sample Input
((a,b,(c,(d,e),f)),g)
-
Sample Output
4 4
#include<stdio.h>
#include<stdlib.h>
typedef char ElemType;
typedef struct Inode{
int tag;
union{
ElemType data;
struct Inode *head;
}val;
struct Inode *tail;
}GLNode;
GLNode *CreateGL(char *&p){
GLNode *g;
char a=*p++;
if(a != '\n'){
g = (GLNode*)malloc(sizeof(GLNode));
if(a == '('){
g->tag = 1;
g->val.head = CreateGL(p);
}
else if(a == ')'){
g = NULL;
}
else{
g->tag = 0;
g->val.data = a;
}
}
else{
g = NULL;
}
a = *p++;
if(g != NULL){
if(a == ',')
g->tail = CreateGL(p);
else
g->tail = NULL;
}
return g;
}
int GLDepth(GLNode *g){
GLNode *p;
int maxg = 0, dep;
if(g->tag == 0)
return 0;
p = g->val.head;
if(p == NULL)
return 1;
while(p != NULL){
if(p->tag == 1){
dep = GLDepth(p);
if(dep > maxg)
maxg = dep;
}
p = p->tail;
}
return(maxg+1);
}
int main(){
char s[100];
gets(s);
char *p=s;
int depth;
GLNode *q;
q = CreateGL(p);
depth = GLDepth(q);
printf("%d\n%d", depth, depth);
return 0;
}
题解:1.用指针指向字符串,方便逐个检索;
2.创建广义表:
广义表数据结构
广义表
3.递归求广义表深度