广义表定义及其实现


广义表定义及其实现

#include<iostream>
#include<cstring>
#include<stdlib.h>
using namespace std;

class GListNode //广义表结构
{
    public:
    int type;
    union
    {
        char data;
        GListNode * sublist;
    };
    GListNode *next;
};
class GList
{public:
    GListNode *head; //头指针
    GListNode *DoCreate(char s[],int &i);//创建广义表
    GListNode *Copy(GListNode *p);//复制广义表
    void Traverse(GListNode *p);//遍历广义表
    void Free(GListNode *p);//释放广义表
    int Depth(GListNode *p);//返回广义表深度

    GList();//创建广义表
    GList(char s[]);
    GList(GList &gl);
    ~GList();
    void Traverse();
    int Length();//广义表长度

};
GList::GList()
{
    head=new GListNode;
    head->type=1;
    head->sublist=head->next=NULL;
}
GListNode * GList::DoCreate(char s[],int &i)
{
    GListNode *p;
    while(s[i]==' '||s[i]==',')
        i++;
    char e=s[i];
    i++;
    if(e=='(')
    {
        p=new GListNode;
        p->type=1;
        p->sublist=DoCreate(s,i);
        p->next=DoCreate(s,i);
        return p;
    }
    if(e==')'||e=='\0')
    {
        return NULL;
    }
    p=new GListNode;
    p->type=0;
    p->data=e;
    p->next=DoCreate(s,i);
    return p;
}
GList::GList(char s[])
{
    int i=0;
    head=DoCreate(s,i);
}
void GList::Traverse(GListNode *p)
{
    if(p==NULL)
    return ;
    if(p->type==0)
    cout<<p->data;
    else
    {
        cout<<"(";
        Traverse(p->sublist);
        cout<<")";
    }
    if(p->next)
        cout<<",";
    Traverse(p->next);
}
void GList::Traverse()
{
    Traverse(this->head);
}
void GList::Free(GListNode * p)
{
    if(p==NULL)
        return ;
    if(p->type==1)
        Free(p->next);
    Free(p->next);
    delete p;
}
GList::~GList()
{Free(head);}
GListNode *GList::Copy(GListNode *p)
{
    if(p==NULL)
        return NULL;
    GListNode *newp=new GListNode;
    newp->type=p->type;
    if(p->type==1)
        newp->sublist=Copy(p->next);
    else
    {
            newp->data=p->data;
            newp->next=Copy(p->next);
    return newp;
    }
    
}
int GList::Length()
{
    GListNode *p;
    int n=0;
    p=head->sublist;
    while(p)
    {
        p=p->next;
        n++;
    }
    return n;
}
int GList::Depth(GListNode *p)
{   
    if(p->type==0)
    return 0;
    int maxdepth=0;
    GListNode * q;
    q=p->sublist;
    while(q)
    {
        depth=Depth(q);
        if(depth>maxdepth)
            maxdepth=depth;
        q=q->next;
    }
    return maxdepth+1;
}
int main()
{

    char s[200];
    cin>>s;
    GList gl(s);
    gl.Traverse();
    system("pause");
    return 0;

}


文章作者: LHL
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 LHL !
评论
 上一篇
示波器实验 示波器实验
数据结构 排队 链表实现和数组实现
2020-10-17 LHL
下一篇 
7-11 玩转二叉树 (25分) 7-11 玩转二叉树 (25分)
7-11 玩转二叉树 (25分)给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
2020-10-15 LHL
  目录