预想中的递归函数出来是没有问题的,但是它只能读到第一个右括号出现,比如我现在的字符串为(a,(b,c),d),它只能输出(a,(b,c))
#include
#include
#define OK 1
#define Error -1
typedef char ElemType;
typedef int Status;
typedef struct GLNode
{
int tag;
union
{
ElemType data;
struct GLNode* sublist;
};
struct GLNode* Link;
}GL;
GL* GLCreat(ElemType* e)
{
GL* h;
ElemType ch=*e;
e++;
if(ch!='\0')//(a,(b,c),d)
{
h=(GL*)malloc(sizeof(GL));
if(ch=='(')
{
h->tag=1;
h->sublist=GLCreat(e);//(,(
}
else if(ch==')')
{
free(h);
h=NULL;
}
else
{
h->tag=0;
h->data=ch;
}
}
else
h=NULL;
ch=*e;
e++;
if(h!=NULL)
{
if(ch==',')
{
h->Link=GLCreat(e);//a,b
}
else
{
h->Link=NULL;//c
}
}
return h;
}
void GLPrint(GL* L)
{
if(L!=NULL)
{
if(L->tag==1)//(a,(b,c),d)
{
printf("(");
if(L->sublist==NULL)
{
printf("");
}
else
{
GLPrint(L->sublist);//(,(
}
}
else
{
printf("%c",L->data);
}
if(L->tag==1)
{
printf(")");
}
if(L->Link!=NULL)
{
printf(",");
GLPrint(L->Link);//a,b,c
}
}
}
int main()
{
ElemType a[]="(a,(b,c),d)";
GL* head=GLCreat(&a);
GLPrint(head);
return 0;
}
这样看看:
GL* GLCreat(ElemType* e)
{
GL* h;
ElemType ch=*e;
e++;
if(ch!='\0')
{
h=(GL*)malloc(sizeof(GL));
if(ch=='(')
{
h->tag=1;
h->sublist=GLCreat(e);
}
else
{
h->tag=0;
h->data=ch;
}
}
else // 到达字符串末尾
h=NULL;
ch=*e;
if(h!=NULL)
{
if(ch==',')
{
h->Link=GLCreat(e+1);
}
else if(ch==')')
{
h->Link=NULL; // 完成当前子表的构造
}
}
return h;
}