求广义表深度(严5.30)

本文介绍了一种使用递归程序来计算广义表深度的方法。通过解析输入的字符串形式的广义表,构建对应的广义表结构,并利用递归算法求得广义表的深度。示例展示了输入为复杂广义表时的处理过程及结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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  
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值