广义表
广义表可同时存储单个元素和广义表,其中存储的单个元素称为 "原子",而存储的广义表称为 "子表"。
一般使用链表实现
typedef struct gnode
{
int tag;
union
{
char data;
struct
{
struct gnode* nextdata;
struct gnode* nextnode;
}gnext;
}subnode;
};
union 共用体,因为同一时间此节点不是原子节点就是子表节点,当表示原子节点时,就使用 atom 变量;反之则使用 ptr 结构体。
初始化 {a,{b,c,d}}
gnode* initgnode()
{
gnode* gn = (gnode*)malloc(sizeof(gnode));
gn->tag = 1;
gnode* gnn = (gnode*)malloc(sizeof(gnode));
gnn->tag = 0;
gnn->subnode.data = 'a';
gn->subnode.gnext.nextdata = gnn;
gnode* gn1 = (gnode*)malloc(sizeof(gnode));
gn1->tag = 1;
gn1->subnode.gnext.nextnode = NULL;
gn->subnode.gnext.nextnode = gn1;
gnode* gn2 = (gnode*)malloc(sizeof(gnode));
gn2->tag = 1;
gn1->subnode.gnext.nextdata = gn2;
gnode* gnn1 = (gnode*)malloc(sizeof(gnode));
gnn1->tag = 0;
gnn1->subnode.data = 'b';
gn2->subnode.gnext.nextdata = gnn1;
gnode* gn3 = (gnode*)malloc(sizeof(gnode));
gn3->tag = 1;
gn2->subnode.gnext.nextnode = gn3;
gnode* gnn2 = (gnode*)malloc(sizeof(gnode));
gnn2->tag = 0;
gnn2->subnode.data = 'c';
gn3->subnode.gnext.nextdata = gnn2;
gnode* gn4 = (gnode*)malloc(sizeof(gnode));
gn4->tag = 1;
gn3->subnode.gnext.nextnode = gn4;
gnode* gnn3 = (gnode*)malloc(sizeof(gnode));
gnn3->tag = 0;
gnn3->subnode.data = 'd';
gn4->subnode.gnext.nextdata = gnn3;
gn4->subnode.gnext.nextnode = NULL;
return gn;
}
广义表的广度和深度计算
void gdsd(gnode* gn, int* gs)
{
gnode* temp = gn;
int gd = 0;
int sd = 0;
int max = 0;
while (temp != NULL)
{
sd = 1;
gnode* temp1 = temp;
while (temp1->subnode.gnext.nextnode != NULL)
{
temp1 = temp1->subnode.gnext.nextdata;
if (temp1->tag == 0)
{
sd++;
break;
}
else
{
sd++;
}
}
if (max < sd)
{
max = sd;
}
gd++;
temp = temp->subnode.gnext.nextnode;
}
gs[0] = gd;
gs[1] = max;
}
广义表复制
gnode* copygnode(gnode* c, gnode* t)
{
if (!c)
{
t = NULL;
}
else
{
t = (gnode*)malloc(sizeof(gnode));
t->tag = c->tag;
if (c->tag == 0)
{
t->subnode.data = c->subnode.data;
}
else{
t->subnode.gnext.nextdata = copygnode(c->subnode.gnext.nextdata, t->subnode.gnext.nextdata);
t->subnode.gnext.nextnode = copygnode(c->subnode.gnext.nextnode, t->subnode.gnext.nextnode);
}
}
return t;
}