开发者社区> 问答> 正文

数据结构中 编写判断两个广义表的递归算法

最好用C语言。谢谢!

展开
收起
知与谁同 2018-07-22 17:53:05 2197 0
2 条回答
写回答
取消 提交回答
  • 有空给你编。
    2019-07-17 22:54:35
    赞同 展开评论 打赏
  • 阿里云开发者社区运营负责人。原云栖社区负责人。
    #include<stdio.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 if(ch==' ')
    g->val.data=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;
    }

    bool same(GLNode *h1,GLNode *h2)
    {
    bool mark;
    if(h1==h2)
    return true;
    else if(h1->tag==h2->tag)
    {
    if(h1->tag==0)
    {
    if(h1->val.data==h2->val.data)
    mark=true;
    else
    mark=false;
    }
    if(h1->tag==1)
    mark=same(h1->val.sublist,h2->val.sublist);
    if(mark)
    {
    if(!(h1->link==NULL && h2->link==NULL))
    {
    if(h1->link!=NULL && h2->link!=NULL)
    mark=same(h1->link,h2->link);
    else
    return false;
    }
    }
    if(mark==false)
    return false;
    else if(mark)
    return true;
    }
    return false;
    }

    void main()
    {
    char *s1="( )",*s2="(a,(b,c))";
    GLNode *g1,*g2;
    g1=CreateGL(s1);
    g2=CreateGL(s2);
    printf("判断两个广义表是否相等:%s\n",same(g1,g2)?"两个广义表相等":"两个广义表不相等");
    }
    2019-07-17 22:54:35
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
如何使用Tair增强数据结构构建丰富在线实时场景 立即下载
Apache Flink 流式应用中状态的数据结构定义升级 立即下载
图解算法小抄 立即下载