广义表求深度与求长度

头文件

#include<stdio.h>
#include<stdlib.h>

#define Status bool
#define OVERFLOW 0
#define OK 1
#define SUCCESS 1
#define UNSUCCESS 0

typedef char AtomType;

结构体


typedef enum {ATOM,LIST} ElemTag;//ATOM=0:原子;LIST=1:子表

typedef struct GLNode {
    ElemTag  tag; 
    union {
      AtomType  atom;
	  struct {struct GLNode  *hp, *tp;} ptr;
 		  }un;
  }GLNode,*GList; //广义表类型

按表头表尾求广义表深度

int GListDepth1(GList L){	//按表头表尾求广义表深度 
/* Return the depth of list */
    int h1,h2;
    if(NULL==L)
        return 1;
    if(ATOM==L->tag)
        return 0;
    h1 = GListDepth1(L->un.ptr.hp)+1;
    h2 = GListDepth1(L->un.ptr.tp);
    return h1>=h2?h1:h2;

元素分解求深度

int GListDepth2(GList L){	//元素分解求深度 
	int dep,max;  
	GLNode *p;
	if(NULL==L) 
		return 1;
	else if(ATOM==L->tag) 
		return 0;
	for(max = 0,p=L;p!=NULL;p=p->un.ptr.tp) {
		dep = GListDepth2(p->un.ptr.hp);
		if(dep>max) 
			max = dep;
	}
	return max+1;
}

按表头表尾分解求长度

int GListLength1(GList L){	//按表头表尾分解求长度 
	int len = 0; GLNode *p;
	if(NULL==L) 
		return len;
	for(len = 1,p = L->un.ptr.tp;p!=NULL; p = p->un.ptr.tp) 
		len++;
	return len;
}

按元素分解广义表求解长度

int GListLength2(GList L){	//按元素分解广义表求解广义表长度 
	int len;
	if(NULL==L)
		len = 0;	//空表长度为0
	else if(NULL==L->un.ptr.tp)
		len = 1;
	else 
		len = GListLength2(L->un.ptr.tp) + 1;
	return len; 

打印广义表

void printGList(GList ls){
    if(ls != NULL){
        if(ls->tag == ATOM)
            printf("%c  " , ls->un.atom) ;
        else{
            printGList(ls->un.ptr.hp) ;
            printGList(ls->un.ptr.tp) ;
        }
    }
}
发布了12 篇原创文章 · 获赞 2 · 访问量 234

猜你喜欢

转载自blog.csdn.net/m0_46140702/article/details/103828552