求广义表深度(严5.30)--------西工大noj

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef enum{ATOM, LIST}ElemType;
typedef struct GLNode{
    ElemType tag;
    union{
        char atom;
        struct{
            struct GLNode *hp,*tp;
        }htp;
    }atom_htp;
}GLNode;
char s[1000];
void Process(char *str, int len, char ** str1, int *len1, char ** str2, int *len2)
{
    int cnt = 0;
    int a = 0;
    for(int i = 0; i < len; i++)
    {
        if(str[i]=='(')
            cnt++;
        if(str[i]==')')
            cnt--;
        if(cnt == 0 && str[i]==',')
            break;
        a++;
    }
    if(a == len)
    {
        (*str1) = str;
        *len1 = a;
        (*str2) = NULL;
        *len2 = 0;
    }
    else
    {
        (*str1) = str;
        *len1 = a;
        (*str2) = str+a+1;
        *len2 = len - a- 1;
    }
}
void Create(GLNode **G, char *str, int len)
{
    if(len==0) *G = NULL;
    else if(len==1)
    {
        *G = (GLNode *)malloc(sizeof(GLNode));
        (*G)->tag = ATOM;
        (*G)->atom_htp.atom = str[0];
    }
    else
    {
        *G = (GLNode *)malloc(sizeof(GLNode));
        (*G)->tag = LIST;
        GLNode * p = *G, *q;
        char *str1, *str2, *str3;
        int len1, len2, len3;//一是当前处理的,二是剩下的,三是起临时作用的
        {//脱去括号
            str = str + 1;
            len = len -2;
        }
        str2 = str;
        len2 = len;
        do
        {
            str3 = str2;
            len3 = len2;
            Process(str3, len3, &str1, &len1, &str2, &len2);
            Create(&(p->atom_htp.htp.hp), str1,len1);
            if(len2 != 0)
            {
                q = (GLNode *)malloc(sizeof(GLNode));
                q->tag = LIST;
                p->atom_htp.htp.tp = q;
                p = q;
            }
        }while(len2!=0);
        p->atom_htp.htp.tp = NULL;

    }

}
int GetHeighth(GLNode* G)
{
    int max = -1;
    int n;
    if(!G)
        return 1;
    if(G->tag==ATOM)
        return 0;
    GLNode *p = G;
    while(p)
    {
        n = GetHeighth(p->atom_htp.htp.hp);
        max = n>max?n:max;
        p = p->atom_htp.htp.tp;
    }
    return max + 1;
}
int main()
{
    scanf("%s",s);
    GLNode * G;
    Create(&G,s, strlen(s));
    int ret = GetHeighth(G);
    printf("%d\n%d",ret,ret);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值