广义表

#include <stdio.h>
#include <stdlib.h>

struct LNode
{
    int tag;                     /*tag = 0代表原子, tag = 1代表子表*/
    union
    {
        char data;
        struct LNode *sublist;   /*定义union代表存储原子的数据或者子表的节点*/
    }val;
    struct LNode *next;
};

void CreatList (struct LNode* *gl)
{
    char ch;
    ch = getchar();
    if(ch == '#')
    {
        *gl = NULL;
    }
    else if(ch == '(')
    {
        *gl = malloc(sizeof(struct LNode));
        (*gl)->tag = 1;
        CreatList(&((*gl)->val.sublist));
    }
    else
    {
        *gl = malloc(sizeof(struct LNode));
        (*gl)->val.data = ch;
        (*gl)->tag = 0;

    }
    ch = getchar();
    if(*gl == NULL)
    {
        ;
    }
    if(ch == ',')
    {
        CreatList(&((*gl)->next));
    }
    else
    {
        (*gl)->next = NULL;
    }
}

void PrintList (struct LNode *gl)
{
    if(gl->tag == 1)
    {
        printf("(");
        if(gl->val.sublist == NULL)
        {
            printf("#");
        }
        else
        {
            PrintList(gl->val.sublist);
        }
        printf(")");
    }
    else
    {
        printf("%c", gl->val.data);
    }
    if(gl->next != NULL)
    {
        printf(",");
        PrintList(gl->next);
    }
}

int LengthList (struct LNode *gl)
{
    int n = 0;
    gl = gl->val.sublist;
    while(gl != NULL)
    {
        n++;
        gl = gl->next;
    }
    return n;
}

int DepthList (struct LNode *gl)
{
    int max = 0;
    if(gl->tag == 0)
    {
         return 0;
    }
    gl = gl->val.sublist;
    if(gl == NULL)
    {
        return 1;
    }
    while(gl != NULL)
    {
        if(gl->tag == 1)
        {
            int dep = DepthList(gl);
            if(dep > max)
                max = dep;
        }
         gl = gl->next;
    }
    return max+1;
}

int main ()
{
    struct LNode *gl;
    int depth, length;
    CreatList(&gl);
    PrintList(gl);
    printf("\n");
    depth = DepthList(gl);
    length = LengthList(gl);
    printf("The list length is : %d\nThe list depth is : %d\n", length, depth);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值