广义表的基本操作

数据结构基础之一:广义表

广义表的基本性质:

①深度:广义表的括号层数

②广义表可表中套表,元素之间的关系体现次序关系和层次关系,线性表是广义表的特例。


若广义表L={d0,d1,d2,d3,d4,...,dn-1};

则,Head(L)=d0;

Tail(L)={d1,d2,d3,d4,....,dn-1};


递归定义:

原子深度=0;

空表深度=1;

广义表深度=max(各元素深度)+1;



/*
Nickname:Rollchuchy
type:广义表 
*/

#include<iostream> 
#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
typedef char datatype;

typedef struct node{
	int atom;
	union{
		datatype data;
		struct node *link;
	}dtype;
	struct node *next;
}Lsnode,*Lslink;

//递归广义表深度 
int ListsDepth(Lslink LS){
	int d,maxd;
	if(LS->atom==0) return 0;//原子深度=0
	Lslink p=LS->dtype.link;
	if(p==NULL) return 1;//空表深度=1,该行代码可去掉 
	maxd=0;
	while(p){
		d=ListsDepth(p);
		if(d>maxd) maxd=d;
		p=p->next; 
	} 
	return maxd+1;
} 

//广义表长度
int ListsLength(Lslink LS){
	if(LS!=NULL){
		return 1+ListsLength(LS->next);
	}else{
		return 0;
	}
} 

void CreatLists(Lslink *LS){
	char ch;
	scanf("%c",&ch);
	/* 若输入为#,则置表头指针为空 */
	if(ch=='#'){
		*LS=NULL;
	}else if(ch=='('){
		*LS=(Lslink)malloc(sizeof(Lsnode));
		(*LS)->atom=1;
		CreatLists(&((*LS)->dtype.link));
	}else{
		*LS=(Lslink)malloc(sizeof(Lsnode));
		(*LS)->atom=0;
		(*LS)->dtype.data=ch;
	}
	scanf("%c",&ch);
	if(*LS==NULL){
	}else if(ch=='\n'){
		(*LS)->next=NULL;
	}else if(ch==','){
		CreatLists(&((*LS)->next));
	}else if(ch==')' || ch==';'){
		(*LS)->next=NULL;
	}
}

void PrintLists(Lslink LS){
	if(LS->atom==1){
		cout<<"(";
		if(LS->dtype.link==NULL){
			cout<<"#";
		}else{
		PrintLists(LS->dtype.link);
		}
		cout<<")";
	}else{
		cout<<LS->dtype.data;
	}
	if(LS->next!=NULL){
		cout<<",";
		PrintLists(LS->next);
	}
}
int main(){
	Lslink LS;
	CreatLists(&LS);
	PrintLists(LS);
	cout<<endl;
	cout<<"广义表长度:"<<endl;
	cout<<ListsLength(LS->dtype.link)<<endl;
	cout<<"广义表深度:"<<endl;
	cout<<ListsDepth(LS->dtype.link)<<endl;
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值