Representation and implementation of recursive data structures of generalized tables -- self-writing Data Structures
The header file glist. h is as follows:
#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
The data structure implementation glist. c is as follows:
/********************** Time: 2014.12.15 Author: XIAO_PING_PING compiling environment: DEV-C + 4.9.2 content: recursive expression and implementation of generalized tables: learn to write data structures *************************/# include
# Include
# Include "glist. h "/* length of the generalized table */int glist_length (pGList pgl) {int length = 0; pgl = pgl-> val. sublist; while (pgl) {length ++; pgl = pgl-> next;} return length;}/* depth of a generalized table */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;}/* create generalized table */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 = tch ;}} else {pgl = NULL;} tch = * (* ch); * ch = * ch + 1; if (pgl) {if (', '= tch) {pgl-> next = creat_glist (ch) ;}else {pgl-> next = NULL ;}} return pgl ;} /* print generalized tables through traversal */void printf_glist (pGList pgl) {if (1 = pgl-> tag) {printf ("("); if (pgl-> val. sublist) {printf_glist (pgl-> val. sublist);} else {printf ("") ;}} else {printf ("% c", pgl-> val. data);} if (1 = pgl-> tag) {printf (")");} if (pgl-> next) {printf (","); printf_glist (pgl-> next );}}}
The test. c file is as follows:
/*************************************** Time: author: XIAO_PING_PING *************************************** */# include
# Include
# Include
# 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 ;}
The running result is as follows: