#include <stdio.h>
#include <stdlib.h>
struct LNode
{
int tag; /*tag = 0代表原子, tag = 1代表子表*/
union
{
char data;
struct LNode *sublist; /*定义union代表存储原子的数据或者子表的节点*/
}val;
struct LNode *next;
};
void CreatList (struct LNode* *gl)
{
char ch;
ch = getchar();
if(ch == '#')
{
*gl = NULL;
}
else if(ch == '(')
{
*gl = malloc(sizeof(struct LNode));
(*gl)->tag = 1;
CreatList(&((*gl)->val.sublist));
}
else
{
*gl = malloc(sizeof(struct LNode));
(*gl)->val.data = ch;
(*gl)->tag = 0;
}
ch = getchar();
if(*gl == NULL)
{
;
}
if(ch == ',')
{
CreatList(&((*gl)->next));
}
else
{
(*gl)->next = NULL;
}
}
void PrintList (struct LNode *gl)
{
if(gl->tag == 1)
{
printf("(");
if(gl->val.sublist == NULL)
{
printf("#");
}
else
{
PrintList(gl->val.sublist);
}
printf(")");
}
else
{
printf("%c", gl->val.data);
}
if(gl->next != NULL)
{
printf(",");
PrintList(gl->next);
}
}
int LengthList (struct LNode *gl)
{
int n = 0;
gl = gl->val.sublist;
while(gl != NULL)
{
n++;
gl = gl->next;
}
return n;
}
int DepthList (struct LNode *gl)
{
int max = 0;
if(gl->tag == 0)
{
return 0;
}
gl = gl->val.sublist;
if(gl == NULL)
{
return 1;
}
while(gl != NULL)
{
if(gl->tag == 1)
{
int dep = DepthList(gl);
if(dep > max)
max = dep;
}
gl = gl->next;
}
return max+1;
}
int main ()
{
struct LNode *gl;
int depth, length;
CreatList(&gl);
PrintList(gl);
printf("\n");
depth = DepthList(gl);
length = LengthList(gl);
printf("The list length is : %d\nThe list depth is : %d\n", length, depth);
return 0;
}
广义表
最新推荐文章于 2022-09-20 17:27:27 发布