c语言数据结构---广义表

#include<stdio.h>
#include<stdlib.h>
typedef struct GNode{//广义表  
	 int NodeTag;      //标志域
    union{           
          char data;
           struct GNode *sublist;
    };
    struct GNode *next;  
}*PGNode,PG;
void CreateGList(PGNode &GL)
{
       char ch;
       scanf("%c", &ch);//读入一个字符,此处只可能读入空格#、左括号或英文字母
       if(ch=='#')//若输入为空格,则置表头指针为空
          {
    GL = NULL;
     
}
       else if(ch=='(')   {
              GL = (PGNode)malloc(sizeof(struct GNode));
             
               GL->NodeTag = 1;
              CreateGList(GL->sublist);
       }
       else{       
              GL =  (PGNode) malloc(sizeof(struct GNode));
               GL->NodeTag = 0;
              GL->data = ch;
       }
       scanf("%c", &ch);//逗号、右括号或分号
       if(GL==NULL)      //若*GL为空,则什么都不做
{
return ;
}
       else if(ch==',')//若输入逗号则递归构造后继表
              {
CreateGList(GL->next);
}
       else if((ch==')') || (ch==';'))
              {
 GL->next = NULL;
}
}


int DepthGList(PGNode GL)
{
       int max=0;
       //遍历表中每一个结点,求出所有子表的最大深度
       while(GL!=NULL)
       {
              if(GL->NodeTag==1){
                     int dep = DepthGList(GL->sublist);
                     if(dep > max)
                            max = dep;
              }
              GL = GL->next;
       }
       return(max + 1);//返回表的深度
}


int LengthGList(PGNode GL)
{
       if(GL!=NULL)
              return(1 + LengthGList(GL->next));
       else
              return(0);
}


void PrintGList(PGNode GL)
{
       
       if(GL->NodeTag==1){   
              printf("(");
              if(GL->sublist==NULL)//若子表为空则输出'#'字符
                     {
printf("#");
   }
              else
                   {
  PrintGList(GL->sublist);
}              
printf(")");
       }
       else//对于单元素结点
            {
  printf("%c", GL->data);
   }       
if(GL->next!=NULL)
       {
              printf(",");//先输出逗号分隔符
              PrintGList(GL->next);//再递归输出后继表
       }
}


int main()
{
	//建议尝试案例(a,b,c,(d,e,f,g,(h,i,j,k,(l,m,n),o),p),q); 
PGNode GL;
int depth,length;
printf("请输入一个广义表,以分号结束 :  ");
CreateGList(GL);
       printf("\n此方法输出的输出广义表->  :");
       PrintGList(GL);
       printf("\n\n");
depth =  DepthGList( GL->sublist );
printf("广义表的深度depth为-> %d \n",depth);
length = LengthGList( GL->sublist );
printf("广义表的长度width为-> %d \n",length);
return 0;
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东箭武

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值