有两种结构的节点:一种是表节点,用以表示列表;一种是原子节点,用以表示原子。若列表不空,则可分解为表头和表尾;反之,一对确定的表头和表尾可以唯一确定列表。因此列表有三个域组成:标志域,两个指针域。而原子节点只需两个域标志域和值域。
“a.h”
#include
#include
#include
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
typedef int Status;
typedef int AtomType;
typedef enum{ATOM,LIST} ElemTag;
typedef struct{
ElemTag tag; //用来区分原子节点和表节点
union{ //原子节点和表节点的联合体
AtomType atom; //原子的值域
struct {
struct GLNode *hp,*tp;
}ptr; //ptr表示节点的指针域,Ptr.hp和ptr.tp指向头和尾
}a;
} *GList,GLNode; //广义表类型的
//称第一个元素为表头,其余的元素为表尾
//主要要用到递归
“b.h”
Status InitGList(GList *L)
{
*L=NULL;
return OK;
}
void DestroyGList(GList *L)
{
GList q1,q2;
if(*L)
if((*L)->tag==ATOM){
free(*L);
(*L)=NULL;
}
else{
q1=(*L)->a.ptr.hp;
q2=(*L)->a.ptr.tp;
free(*L);
*L=NULL;
DestroyGList(&q1);
DestroyGList(&q2);
}
}
Status CopyGList(GList *T,GList L)
{
if(!L)
*T=NULL;
else{
*T=(GList)malloc(sizeof(GLNode));
if(!(*T))
exit(0);
if(L->tag==ATOM)
(*T)->a.atom=L->a.atom;
else{
CopyGList(&(*T)->a.ptr.hp,L->a.ptr.hp);
CopyGList(&(*T)->a.ptr.tp,L->a.ptr.tp);
}
}
return OK;
}
Status InsertFirst_GL(GList *L,GList e)
{
GList p=(GList)malloc(sizeof(GLNode));
if(!p)
exit(0);
p->tag=LIST;
p->a.ptr.hp=e;
p->a.ptr.tp=*L;
*L=p;
return OK;
}
Status DeleteFirst_GL(GList *L,GList *e)
{
GList p;
*e=(*L)->a.ptr.hp;
p=*L;
*L=(*L)->a.ptr.tp;
free(p);
return OK;
}
Status Traverse_GL(GList L)
{
if(L)
if(L->tag==ATOM)
printf(" %d ",L->a.atom);
else{
Traverse_GL(L->a.ptr.tp);
Traverse_GL(L->a.ptr.hp);
}
return OK;
}
GList GetHead(GList L)
{
GList p,q;
if(!L)
exit(0);
q=L->a.ptr.tp; //先用q记录L的尾结点
L->a.ptr.tp=NULL;
CopyGList(&p,L);
L->a.ptr.tp=q;
return p;
}
GList GetTail(GList L)
{
GList p;
if(!L)
exit(0);
CopyGList(&p,L->a.ptr.tp); //直接复制为结点
return p;
}
int GListDepth(GList L)
{
int max,dep;
GList p;
if(!L) //空表返回深度为1
return 1;
if(L->tag==ATOM)
return 0; //非空表返回深度为0
for(max=0,p=L;p;p=p->a.ptr.tp){
dep=GListDepth(p); //dep算出来的是头结点的深度
if(dep>max) //如果dep
max=dep; //而在尾结点中
}
return max+1;
}
int GListLength(GList L)
{
int i=0;
if(!L)
return 0;
if(L->tag==ATOM)
return 1;
while(L){
L=L->a.ptr.tp; //L到下一个尾结点
i++;
}
return i;
}
“main.c”
#include"a.h"
#include"b.h"
void main()
{
GList L;
GList T;
InitGList(&L);
InitGList(&T);
}