#include<iostream>
using namespace std;
typedef char AtomType;
enum ElemTag{ATOM,LIST};
typedef struct GLNode
{
ElemTag tag;
union
{
AtomType atom;
GLNode *pHead;
};
GLNode *pTail;
}GLNode,*GList;
void InitGList(GList &L)
{
L = NULL;
}
void DestroyGList(GList &L)
{
GList ph, pt;
if (L)
{
if (L->tag == LIST)
ph = L->pHead;
else
ph = NULL;
pt = L->pTail;
delete L;
L = NULL;
DestroyGList(ph);
DestroyGList(pt);
}
}
void CopyGList(GList &T, GList L)
{
if (!L)
T = NULL;
else
{
T = new GLNode;
T->tag = L->tag;
if (L->tag == ATOM)
T->atom = L->atom;
else
CopyGList(T->pHead, L->pHead);
if (!(L->pTail))
T->pTail = NULL;
else
CopyGList(T->pTail, L->pTail);
}
}
int GListLength(GList L)
{
int len = 0;
GList p;
if (L->tag == LIST&&!(L->pHead))
return 0;
else if (L->tag == ATOM)
return 1;
else
{
p = L->pHead;
do
{
++len;
p = p->pTail;
} while (p);
return len;
}
}
bool GListEmpty(GList L)
{
if (!L || L->tag == LIST&&!(L->pHead))
return true;
else
return false;
}
int GListDepth(GList L)
{
int max, dep;
GList p;
if (GListEmpty(L))
return 1;
else if (L->tag == ATOM)//递归之前是不会出现的
return 0;
else
{
for (max = 0, p = L->pHead; p; p = p->pTail)
{
dep = GListDepth(p);
if (dep > max)
max = dep;
}
return max + 1;
}
}
GList GetHead(GList L)
{
GList h;
InitGList(h);
if (GListEmpty(L))
return NULL;
else
{
h = new GLNode;
h->tag = L->pHead->tag;
h->pTail = NULL;
if (h->tag == ATOM)
h->atom = L->pHead->atom;
else
CopyGList(h->pHead, L->pHead->pHead);
return h;
}
}
GList GetTail(GList L)
{
GList t;
if (!L)
return NULL;
else
{
t = new GLNode;
t->tag = LIST;
t->pTail = NULL;
CopyGList(t->pHead, L->pHead->pTail);
return t;
}
}
void InsertFirst(GList &L, GList pe)
{
GList p = L->pHead;
L->pHead = pe;
pe->pTail = p;
}
void DeleteFirst(GList &L, GList &pe)
{
if (L)
{
pe = L->pHead;
L->pHead = pe->pTail;
pe->pTail = NULL;
}
else
pe = L;
}
void VisitAtom(AtomType a)
{
cout << a << " ";
}
void GListPrint(GList L)
{
GList ph;
if (L)
{
if (L->tag == ATOM)
{
VisitAtom(L->atom);
ph = NULL;
}
else
{
ph = L->pHead;
GListPrint(ph);
GListPrint(L->pTail);
}
}
}
数据结构之广义表(扩展线性链表)的基本操作
最新推荐文章于 2022-06-29 10:55:05 发布