求广义表深度(严5.30)--------西工大noj

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef enum{ATOM, LIST}ElemType;
typedef struct GLNode{
ElemType tag;
union{
char atom;
struct{
struct GLNode *hp,*tp;
}htp;
}atom_htp;
}GLNode;
char s[1000];
void Process(char *str, int len, char ** str1, int *len1, char ** str2, int *len2)
{
int cnt = 0;
int a = 0;
for(int i = 0; i < len; i++)
{
if(str[i]=='(')
cnt++;
if(str[i]==')')
cnt--;
if(cnt == 0 && str[i]==',')
break;
a++;
}
if(a == len)
{
(*str1) = str;
*len1 = a;
(*str2) = NULL;
*len2 = 0;
}
else
{
(*str1) = str;
*len1 = a;
(*str2) = str+a+1;
*len2 = len - a- 1;
}
}
void Create(GLNode **G, char *str, int len)
{
if(len==0) *G = NULL;
else if(len==1)
{
*G = (GLNode *)malloc(sizeof(GLNode));
(*G)->tag = ATOM;
(*G)->atom_htp.atom = str[0];
}
else
{
*G = (GLNode *)malloc(sizeof(GLNode));
(*G)->tag = LIST;
GLNode * p = *G, *q;
char *str1, *str2, *str3;
int len1, len2, len3;//一是当前处理的,二是剩下的,三是起临时作用的
{//脱去括号
str = str + 1;
len = len -2;
}
str2 = str;
len2 = len;
do
{
str3 = str2;
len3 = len2;
Process(str3, len3, &str1, &len1, &str2, &len2);
Create(&(p->atom_htp.htp.hp), str1,len1);
if(len2 != 0)
{
q = (GLNode *)malloc(sizeof(GLNode));
q->tag = LIST;
p->atom_htp.htp.tp = q;
p = q;
}
}while(len2!=0);
p->atom_htp.htp.tp = NULL;
}
}
int GetHeighth(GLNode* G)
{
int max = -1;
int n;
if(!G)
return 1;
if(G->tag==ATOM)
return 0;
GLNode *p = G;
while(p)
{
n = GetHeighth(p->atom_htp.htp.hp);
max = n>max?n:max;
p = p->atom_htp.htp.tp;
}
return max + 1;
}
int main()
{
scanf("%s",s);
GLNode * G;
Create(&G,s, strlen(s));
int ret = GetHeighth(G);
printf("%d\n%d",ret,ret);
return 0;
}
本文来自博客园,作者:心坚石穿,转载请注明原文链接:https://www.cnblogs.com/xjsc01/p/16438240.html

浙公网安备 33010602011771号