首页 > 代码库 > 广义表的递归数据结构的表示与实现--自己写数据结构

广义表的递归数据结构的表示与实现--自己写数据结构

    文件glist.h头文件如下

#ifndef _GLIST_H_#define _GLIST_H_typedef enum {ATOM,LIST}ElemTag;typedef struct _GList{    ElemTag tag;        union     {        char data;        struct _GList *sublist;         }val;        struct _GList *next;}GList,*pGList;int glist_length(pGList pgl);int glist_depth(pGList pgl);pGList creat_glist(char **ch); void printf_glist(pGList pgl); #endif


数据结构实现glist.c如下

/************************时间:2014.12.15作者:XIAO_PING_PING编译环境:DEV-C++ 4.9.9.2 内容:广义表的递归表示与实现功能:学习写数据结构 *************************/#include <string.h>#include <stdlib.h>#include "glist.h"/*广义表的长度*/int glist_length(pGList pgl){    int length = 0;        pgl = pgl->val.sublist;              while(pgl)    {        length++;        pgl = pgl->next;          }        return length;}/*广义表的深度*/int glist_depth(pGList pgl){    int max = 0,depth;        if(0 == pgl->tag)    {        return 0;         }        pgl = pgl->val.sublist;    if(!pgl)    {        return 1;            }        while(pgl)    {        if(pgl->tag)        {            depth = glist_depth(pgl);             if(depth > max)             {                max = depth;                     }               }        pgl = pgl->next;    }        return max+1;} /*创建广义表*/ pGList creat_glist(char **ch){    pGList pgl;        if(NULL == ch)    {        return ;    }          char tch = *(*ch);     *ch = *ch + 1;        if('\0' != tch)    {        pgl = (GList *)malloc(sizeof(GList));           if('(' == tch)        {                 pgl->tag = LIST;            pgl->val.sublist = creat_glist(ch);        }        else if(')' == tch)        {            pgl = NULL;        }        else        {            pgl->tag = ATOM;            pgl->val.data = http://www.mamicode.com/tch;    >


测试文件test.c如下:

/***************************************时间:2014.12.15作者:XIAO_PING_PING****************************************/#include <conio.h>#include <stdlib.h>#include <string.h>#include "glist.h"int main(){    int length,depth;    char *s="(a,(b,c,d),(d,l),d,p))";     pGList gl;         gl = creat_glist(&s);    length = glist_length(gl);    depth = glist_depth(gl);    printf("length = %d,depth = %d\n",length,depth);    printf_glist(gl);        getch();    return 0;         }


运行结果如下:

 

 

广义表的递归数据结构的表示与实现--自己写数据结构