数据结构与算法之广义表的基本运算

广义表
李春葆系列

#include<stdio.h>
#include<iostream>
#include<stdlib.h>
using namespace std; 
typedef struct lnode
{
	int tag;
	union{
		char data;
		struct lnode * sublist;
	} val;
	struct lnode * link;
}GLNode;

int GLLength(GLNode *g)//长度 
{
	int n=0;
	GLNode *g1;
	g1=g->val.sublist;
	while(g1!=NULL)
	{
		n++;
		g1=g1->link;
	}
	return n;
}
int GLDepth(GLNode*g)//深度 
{
	GLNode *g1;
	int maxd=0,dep;
	if(g->tag==0)
	{
		return 0;
	}
	g1=g->val.sublist;
	if(g1==NULL)
	{
		return 1;
	}
	while(g1!=NULL)
	{ 
		if(g1->tag==1)
		{
			dep=GLDepth(g1);
			if(dep>maxd)
			{
				maxd=dep;
			}
			
		}
		g1=g1->link;
	}
	return (maxd+1);
}

void DispGL(GLNode *g)//输出广义表 
{
	if(g!=NULL)
	{
		if(g->tag==0)
		{
			printf("%c",g->val.data);
		}
		else
		{
			printf("(");
			if(g->val.sublist==NULL)
			{
				printf("#");
			}
			else
			{
				DispGL(g->val.sublist);
			}
			printf(")");
		}
		if(g->link!=NULL)
		{
			printf(",");
			DispGL(g->link); 
		}
	}
}
GLNode *CreatGL(char *&s)
{
	GLNode *g;
	char ch=*s++;
	if(ch!='\0') 
	{
		g=(GLNode *)malloc(sizeof(GLNode));
		if(ch=='(')
		{
			g->tag=1;
			g->val.sublist=CreatGL(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=CreatGL(s);
		}
		else
		{
			g->link=NULL;
		}
	}
	return g;
}
void DestroyGL(GLNode *& g)//递归释放广义表 
{
	GLNode *g1,*g2;
	g1=g->val.sublist;
	while(g1!=NULL)
	{
		if(g1->tag==0)
		{
			g2=g1->link;
			free(g1);
			g1=g2;
		}
		else
		{
			g2=g1->link;
			DestroyGL(g1);
			g1=g2;
		}
	}
	free(g);
}
char Max(GLNode *g) 
{ 
 char max,maxx; 
 if (g!=NULL) 
	{ if (g->tag==0) 
		{ 
		    max=Max(g->link); 
		    if(g->val.data>max)
		    {
		    	 return g->val.data; 
			}
			else
			{
				return max;
			}

		} else 
			{ max=Max(g->val.sublist);
			  maxx=Max(g->link); 
			  if(max>maxx)
			  {
			  	return max;
			  }
			  else
			  {
			  	return maxx;
			  }
			}
	} 
	else 
		return 0; 
}
int main()
{
    GLNode *s;
    char *g="(b,(b,a,(#),d),((a,b),c,((#))))";
    s=CreatGL(g);
    printf("g:");
	DispGL(s);
    printf("\n");
    printf("%d\n",GLLength(s));
    printf("%d\n",GLDepth(s));
    printf("%c", Max(s)); 
    DestroyGL(s);
}
posted @ 2019-11-07 21:24  AmosAlbert  阅读(376)  评论(0编辑  收藏  举报