1、递归实现广义表的创建以及遍历
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<string.h>
#include<malloc.h>
#define AtomType int
typedef enum{HEAD,ATOM,CHILDLIST}ElemType;
typedef struct GLNode
{
ElemType tag;
union{
AtomType atom;
struct GLNode *hp;
};
struct GLNode *tp;
}GLNode;
typedef GLNode *GenList;
void InitGenList(GenList &gl)
{
gl = NULL;
}
bool sever(char *sub,char *hsub)
{
//printf("%s \n %s \n",sub,hsub);
if(*sub == '\0' || strcmp(sub,"()")==0) //空串或者第一个元素为空表
{
hsub[0] = '\0';
return true;
}
int n = strlen(sub); //获取截取后的字符串的长度
int i = 0;
char ch = sub[0];
int k = 0;
while(i<n && (ch!=','|| k != 0)) //截取首节点并进行分割
{
if(ch == '(')
{
k++;
}else if(ch == ')')
{
k--;
}
i++;
ch = sub[i];
}
if(i < n) //进行截取操作并进行尾节点的更新
{
sub[i] = '\0';
strcpy(hsub,sub);
strcpy(sub,sub+i+1);
}else if(k != 0){ //字符串内括号不匹配输入错误
return false;
}else{
strcpy(hsub,sub);
sub[0] = '\0';
}
return true;
}
void CreateGenList(GenList &gl,char *str)
{
int n = strlen(str);
char *sub = (char*)malloc(sizeof(char) * (n-2)); //为截取字符串括号中间的内容分配空间
char *hsub = (char*)malloc(sizeof(char) * (n-2)); //为截取表头元素分配内存空间
assert(sub != NULL && hsub != NULL);
strncpy(sub,str+1,n-2); //截取操作
sub[n-2] = '\0'; //设置截取后的字符串的结束字符
//printf("%s",sub);
if(gl == NULL) //广义表为空时,申请头结点并返回
{
gl = (GLNode*)malloc(sizeof(GLNode));
assert(gl != NULL);
gl->tag = HEAD;
gl->hp = gl->tp = NULL;
}
GLNode *p = gl; //当广义表不为空时,保存表头节点
while(strlen(sub) != 0) //从截取的字符串中遍历
{
p = p->tp = (GLNode*)malloc(sizeof(GLNode)); //为新节点分配内存空间
assert(p != NULL);
p->hp = p->tp = NULL; //新结点的初始化
//printf("%s",sub);
if(sever(sub,hsub)) //截取头结点并判断的相关操作
{
// printf("%s",hsub);
if(hsub[0] == '(') //当前节点为子表情况
{
p->tag = CHILDLIST;
CreateGenList(p->hp,hsub); //递归操作----进行子表的创建
}else{ //原子节点的相关操作
p->tag = ATOM;
p->atom = atoi(hsub);
}
}
}
}
//实现对广义表的遍历
void ShowGenList(GenList &gl)
{
GLNode *p = gl->tp;
printf("(");
while(p != NULL)
{
if(p->tag == ATOM)
{
printf("%d",p->atom);
if(p->tp != NULL)
printf(",");
p = p->tp;
}
else if(p->tag == CHILDLIST)
{
ShowGenList(p->hp);
if(p->tp != NULL)
{
printf(",");
}
p = p->tp;
}
}
printf(")");
}
//判空
bool GenListEmpty(GenList &gl)
{
return gl->hp==NULL;
}
int GenListLength(GenList &gl)
{
int length = 0;
GLNode *p = gl->tp;
while(p != NULL)
{
length++;
p=p->tp;
}
return length;
}
int GenListDepth(GenList &gl)
{
if(gl->tp == NULL)
return 1;
GLNode *p = gl->tp;
int maxdepth = 0;
int dep;
while(p != NULL)
{
if(p->tag == CHILDLIST)
{
dep = GenListDepth(p->hp->tp);
if(dep > maxdepth)
{
maxdepth = dep;
}
}
p = p->tp;
}
return maxdepth+1;
}
int main()
{
GenList gl;
InitGenList(gl);
char *ga = "(1,2,3)";
char *gb = "(1,(3,4))";
char *gc = "(1,(2),3)";
char *gd = "()";
char *ge = "((1,2,3))";
char *gf = "(1,(2,(3,4)),5)";
CreateGenList(gl,gf); //正确实现字符串的截取操作
ShowGenList(gl);
int length = GenListLength(gl);
printf("\n%d" ,length);
int depth = GenListDepth(gl);
printf("\n%d" ,depth);
return 0;
}