第9周项目4广义表算法库及应用2

来源:互联网 发布:face nginx 编辑:程序博客网 时间:2024/05/21 05:44

算法及代码:

#ifndef GLIST_H_INCLUDED#define GLIST_H_INCLUDEDtypedef char ElemType;typedef struct lnode{    int tag;                    //节点类型标识    union    {        ElemType data;          //原子值        struct lnode *sublist;  //指向子表的指针    } val;    struct lnode *link;         //指向下一个元素} GLNode;                       //广义表节点类型定义int GLLength(GLNode *g);        //求广义表g的长度int GLDepth(GLNode *g);     //求广义表g的深度GLNode *CreateGL(char *&s);     //返回由括号表示法表示s的广义表链式存储结构void DispGL(GLNode *g);                 //输出广义表g#endif // GLIST_H_INCLUDED#include <stdio.h>#include "glist.h"int atomnum(GLNode *g)  //求广义表g中的原子个数{    if (g!=NULL)    {        if (g->tag==0)            return 1+atomnum(g->link);        else            return atomnum(g->val.sublist)+atomnum(g->link);    }    else        return 0;}ElemType maxatom(GLNode *g)             //求广义表g中最大原子{    ElemType max1,max2;    if (g!=NULL)    {        if (g->tag==0)        {            max1=maxatom(g->link);            return(g->val.data>max1?g->val.data:max1);        }        else        {            max1=maxatom(g->val.sublist);            max2=maxatom(g->link);            return(max1>max2?max1:max2);        }    }    else        return 0;}int main(){    GLNode *g;    char *s="(b,(b,a,(#),d),((a,b),c((#))))";    g = CreateGL(s);    DispGL(g);    printf("\n");    printf("原子个数 :%d\n", atomnum(g));    printf("最大原子 :%c\n", maxatom(g));    return 0;}


运行结果:

 

 

 

 

0 0
原创粉丝点击