首页 > 代码库 > 广义表的递归数据结构的表示与实现--自己写数据结构
广义表的递归数据结构的表示与实现--自己写数据结构
文件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; }
运行结果如下:
广义表的递归数据结构的表示与实现--自己写数据结构
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。