广义表的建立

/*

function:

1.Create a GeneralizedList

2.Copy a GeneralizedList

3.Get the depth of a GeneralizedList

*/

#include<iostream>

#include<string.h>

using namespace std;


typedef struct GeneralizedList

{

int tag;//case 0,single list;case 1,multi list

union{

char atom;

struct{

GeneralizedList *hp;

GeneralizedList *tp;

}Mlist;

};

}Glist;


void SubString(char *sub,char *str,int start,int number);

void CreateGlist(Glist *&T,char *str);

void server(char *substr,char *str);//find the very first commas of this string


int main()

{

char str[]="((),(e),(a,(b,c,d)))";

Glist *T;

CreateGlist(T,str);

return 0;

}

void CreateGlist(Glist *&T,char *str)

{

Glist *p,*q;

char *sub=new char[strlen(str)];

char *subtwo=new char[strlen(str)];

if(strcmp(str,"()")==0)

{

T=NULL;

}

else

{

//CreateNode

T=new Glist;T->Mlist.hp=NULL;T->Mlist.tp=NULL;

if(strlen(str)==1)

{

   T->tag=0;

T->atom=str[0];

}

else

{

   T->tag=1;

   p=T;

//eliminate bracket

SubString(sub,str,1,strlen(str)-2);

do

{

                server(subtwo,sub);//分离头尾,将头放入subtwo中,将尾放入sub中 

CreateGlist(p->Mlist.hp,subtwo); q=p;//创新串

                if(strlen(sub)!=0)

                {

                p=new Glist;p->Mlist.hp=NULL;p->Mlist.tp=NULL;

                p->tag=1;

                q->Mlist.tp=p;

                }

}while(strlen(sub)!=0);

q->Mlist.tp=NULL;

}

}

}

void server(char *substr,char *str)

{

int k=0;//save the bracket match

int i=0,comma;

int flag=0;

int length=strlen(str);

while(str[i]!='\0'&&(k!=0||flag==0))

{

flag=0;

   if(str[i]=='(') k++;

   if(str[i]==')') k--;

   if(str[i]==',') 

   {

   comma=i;

   flag=1;

}

i++;

}

if(i!=length)

{

SubString(substr,str,0,comma);

substr[comma]='\0';

SubString(str,str,comma+1,length);

str[length-comma-1]='\0';

}

else

{

strcpy(substr,str);

str[0]='\0';

}

}

void SubString(char *sub,char *str,int start,int number)//将从start开始的number个数字复制到sub中去 

{

int i;

for(i=0;i<number;i++) sub[i]=str[start+i];

sub[i]='\0';

}


你可能感兴趣的:(广义表的建立)