数据结构之广义表(扩展线性链表)的基本操作

来源:互联网 发布:lamb动作数据百度云 编辑:程序博客网 时间:2024/06/05 08:02
#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;elseph = 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;elseCopyGList(T->pHead, L->pHead);if (!(L->pTail))T->pTail = NULL;elseCopyGList(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;elsereturn 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;elseCopyGList(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;}elsepe = 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);}}}

0 0