广义表的特点:
1、广义表的元素可以是子表也可以是数值
2、广义表可以被其他广义表共享
3、广义表具有递归性
广义表的表头和表尾
表头是表中第一个元素
表尾是广义表除去第一个元素后剩下元素构成的广义表
广义表的长度和深度
长度:广义表中元素的个数,其中元素包括原子和子表,原子和子表都表示一个元素
深度:广义表中广括号的重数,子表的子表的最大个数
广义表的存储结构
由于广义表元素的不确定性,因此用链表存储结构,有两种链式结点
表结点(元素是子表)和原子结点(元素是数值)
class GLNode {
boolean tag; // 原子结点和表结点的标志位
String atom; // 原子结点的数据域
GLNode sublist; // 表结点的数据域
GLNode next; // 下一个结点的指针域
GLNode(boolean tag, String atom, GLNode sublist, GLNode next) {
this.tag = tag; // 标志位
if (tag){ // tag==true,表结点
this.atom = null;
this.sublist = sublist;
} else if (!tag){ // tag==false,原子结点
this.sublist = null;
this.atom = atom;
}
this.next = next; // next指针域
}
}
// 以上GLNode等价于以下两种结点
class AtomNode {
boolean tag =false; // 标志位置false
String atom;
GLNode sublist =null; // 表结点的数据域置空
GLNode next;
}
class subListNode {
boolean tag =true; // 标志位置true
String atom =""; // 原子结点的数据域置空
GLNode sublist;
GLNode next;
}
创建广义表
创建广义表类似于创建二叉树的过程,深度优先,递归创建
public GLNode create() {
System.out.println("是否继续添加结点('#'退出)?");
String str = sc.nextLine();
if ("#".equals(str)) // 广义表为空
return null;
GLNode GL;
System.out.println("输入此结点是表结点(true)还是原子结点(false)?");
String tagStr = sc.nextLine();
boolean tag = Boolean.parseBoolean(tagStr);
if (tag){ // 表结点
GL = new GLNode(tag, null, create(), create());
} else { // 原子结点
System.out.println("输入原子结点的数值:");
String atom = sc.nextLine();
GL = new GLNode(tag, atom, null, create());
}
return GL;
}
广义表的操作
取表头
// 取表头
public void GetHead(GLNode list) {
if (list == null) // 表为空
return;
if (list.tag){ // head是子表
display(list.sublist); // 打印子表
} else if (!list.tag) { // head是原子
System.out.println("Head:" + list.atom); // 打印头元素
}
}
取表尾
// 取表尾
public void GetTail(GLNode list) {
if (list == null) // 表为空
return;
if (list.next == null) // 表的下一个结点是空
System.out.println("()"); // 表尾是空表
if (list.next != null) // 表的下一个结点非空
display(list.next);
}
求广义表的长度
// 求广义表的长度
public int getLength(GLNode list) {
int length =0;
GLNode pointer = list;
while (pointer!=null) {
length++;
pointer = pointer.next;
}
return length;
}
求广义表的深度
// 求广义表的深度
public int getDepth(GLNode list) {
GLNode pointer = list;
int max = 0;
int dep_num = 0;
while (pointer !=null){
if (pointer.tag) { // 结点是子表
dep_num = getDepth(pointer.sublist);
if (dep_num > max)
max = dep_num;
}
pointer = pointer.next;
}
return max+1;
}