数据结构基础之一:广义表
广义表的基本性质:
①深度:广义表的括号层数
②广义表可表中套表,元素之间的关系体现次序关系和层次关系,线性表是广义表的特例。
若广义表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;
}