#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int A_L;//使用枚举不熟练,A_T代表Atom或List,0为Atom,1为List
Node *before;//额外创建一个指针指向之前
Node *tail;
union
{
Node *down;
char data;
};
}Node;
void CreatLists (Node *pre)
{ //初始化后创建一个广义表
char s,ss=0;
Node *cur;//一下分别讨论字符串中出现各种字符的情况
if ((s=getchar())==',')
{
ss=s;
s=getchar();
}
if (s>='a'&&s<='z')//如果是字母的情况
{
cur =(Node *)malloc (sizeof(Node));
if (ss==',')
{
pre->tail=cur;
}
else
{
pre->down=cur;
}
cur->before=pre;
cur->data=s;
cur->tail=NULL;
cur->A_L=1;
CreatLists (cur);
}
else
{
if (s=='(')//如果是左括号
{
cur =(Node *)malloc (sizeof(Node));
if (ss==',')
{
pre->tail=cur;
}
else
{
pre->down=cur;
}
cur->before=pre;
cur->down=NULL;
cur->tail=NULL;
cur->A_L=0;
CreatLists (cur);//递归创建
}
else
{
if (s==')')//如果是右括号
{
while (pre->A_L||pre->tail)
{
pre=pre->before;
}
CreatLists (pre);
}
}
}
}
void creatL (Node *head)
{//广义表的初始化
head->A_L=0;
head->down=NULL;
head->tail=NULL;
head->before=NULL;
CreatLists(head);//初始化后建立广义表
}
int getDepth (Node *node)
{ //得到广义表的深度,通过递归调用
int max=0,depth;
Node *p;
for (p=node->tail;p;p=p->tail)
{
if (p->A_L)
{
depth=0;//
}
else
{
if (p->down)
{
depth=getDepth(p->down)+1; //递归调用得到下一层的深度
}
else
{
depth=1;
}
}
max=depth>max?depth:max;
}
if (node->A_L)
{
depth=0;
}
else
{
if (node->down)
{
depth=getDepth(node->down)+1;
}
else
{
depth=1;
}
}
return max=depth>max?depth:max;
}
int main()
{
Node head;
int depth;
creatL(&head);//创建广义表
depth=getDepth(head.down);
printf ("%d\n%d",depth,depth);
return 0;
}
西北工业大学NOJ数据结构—014求广义表深度
最新推荐文章于 2022-04-16 14:21:54 发布