广义表的实现

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
struct GLNode
{
    int tag;//节点类型标记
    union
    {
        char data;//原子值
        struct GLNode *sublist;//指向子表的指针
    }val;
    struct GLNode *link;//指向下一个元素
};
GLNode *GLCreate(char *&s)
{
	GLNode *g;
	char ch=* s++;
    if(ch!='\0')
    {
        g=(GLNode *)malloc(sizeof(GLNode));
        if(ch=='(')
        {
            g->tag=1;
            g->val.sublist=GLCreate(s);
        }
        else if(ch==')')
            g=NULL;
        else if(ch=='#')
            g=NULL;
        else
        {
            g->tag=0;
            g->val.data=ch;
        }
    }
    else
        g=NULL;
	ch=*s++;
    if(g!=NULL)
        if(ch==',')
            g->link=GLCreate(s);
        else
            g->link=NULL;
    return g;
}
int GLLength(GLNode *g)//求广义表长度非递归
{
    int gCount=0;
    GLNode *g1=g->val.sublist;
    while(g1!=NULL)
    {
        gCount++;
        g1=g1->link;
    }
    return gCount;
}
int GLLength_recursion(GLNode *g)//求长度递归
{
    if(!g)
        return 1;
    return GLLength_recursion(g->link)+1;
}
int GLDepth(GLNode *g)
{
    GLNode *g1;
    int max=0,dep;
    if(g->tag==0)//为原子时
        return 0;
    g1=g->val.sublist;//g1指向表的第一个元素
    if(g1==NULL)//为空表时
        return 1;
    while(g1!=NULL)//遍历表中每个元素
    {
        if(g1->tag==1)//元素为子表的情况
        {
            dep=GLDepth(g1);
            if(dep>max)
                max=dep;
        }
        g1=g1->link;//指向下一个元素
    }
    return (max+1);
}
void GLDisplay(GLNode *g)
{
    if(g!=NULL)//表不为空
    {
        if(g->tag==0)//为原子时直接输出
            cout<<g->val.data<<" ";
        else
        {
            cout<<"(";
            if(g->val.sublist==NULL)
                cout<<"#";
            else
                GLDisplay(g->val.sublist);
            cout<<")";
        }
        if(g->link!=NULL)
        {
            cout<<",";
            GLDisplay(g->link);
        }
    }
}
int main()
{
    GLNode *g=NULL;
	char *s="((a,b),(c,d))";
	g=GLCreate(s);
    cout<<"广义表的深度为:"<<GLDepth(g)<<endl;
    cout<<"广义表的长度为:"<<GLLength(g)<<endl;
    cout<<"广义表的长度为:"<<GLLength_recursion(g)<<endl;
	cout<<"广义表的内容为:";
	GLDisplay(g);
	cout<<endl;
    return 0;
}


运行结果:

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值