//CTest.cpp: Defines the entry point of the console application. //#include"stdafx.h"#include<iostream>#include<string.h>#include<stdio.h>using namespaceStd;typedefCharElemtype;structglnode{BOOLTag//flag Bitunion{//table header pointer field for a range or child tableelemtype data; Glnode*sublist; }; Glnode*next;};//used for testing (a, (b, (c)), (#), ((D,e))), F, (g));//To find the length of a generalized table is to find the length of a single linked list .intLenth (Glnode *GL) { if(gl!=NULL) { return 1+lenth (gl->next); }Else{ return 0; }}//To find the length of a generalized table is to find the length of a single linked list .intDepth (Glnode *GL) { intmax=0; while(gl!=NULL) { if(gl->tag==true){ intDEP = Depth (gl->sublist); if(Dep>max) max=DEP; } GL=gl->Next; } returnmax+1;}//Create a generalized tablevoidCreate (glnode* &GL) { CharCh//read a characterCin>>ch; //If # is entered, the GL is empty if(ch=='#') gl=NULL; //If the input is an opening parenthesis, the child table node pointed by GL is established and the table is recursively constructed. Else if(ch='(') {GL=NewGlnode; GL->tag=true; Create (GL-sublist); } Else{GL=NewGlnode; GL->tag=false; GL->data=ch; } //the characters read in here are Fu Bi comma, right parenthesis, or semicolonCin>>ch; //If GL is empty, the character entered at this time must be ') ', then nothing is done if(gl==NULL); //recursively constructs a successor table if the input is a comma Else if(ch==',') Create (gl->next); //if the input is a closing parenthesis or semicolon, the subsequent pointer field of GL is empty Else if((ch==')')|| (ch==';')) gl->next=NULL;}//Print out generalized tablevoidPrint (Glnode *GL) { if(gl->tag==true) {cout<<'(';//for table nodes, the opening parenthesis is first exported as the start symbol . if(gl->sublist==NULL) cout<<'#';//If the Word table pointer is empty, the output ' # ' character ElsePrint (GL->sublist);//if it is a non-empty Word table, the table is output recursivelycout<<')';//when the output of a Word table is finished, the closing parenthesis should be output as a terminator } Elsecout<<gl->data;//for a single-element node, output the value of the node if(Gl->next!=null) {//output The successor table of the GL nodecout<<',';//after the parentheses and the delimiters are first outputPrint (Gl->next);//re-recursive output successor table }}int_tmain (intARGC, _tchar*argv[]) {Glnode*g=NULL; Create (g); Print (g); cout<<Endl; cout<<"the length of a generalized table:"<<lenth (g->sublist) <<Endl; cout<<"the depth of a generalized table:"<<depth (g->sublist) <<Endl; System ("Pause"); return 0;}
Data structure C + + generalized table