java编程:实现(a,(),c,(a,(c,d)),b)广义表存储与输出。
时间: 2023-10-13 13:06:39 浏览: 49
好的,这是一个关于Java编程的问题,我可以回答。在Java中,我们可以使用链式结构来实现广义表的存储与输出。具体实现方式可以参考以下代码:
```
class Node {
String value; // 存储节点的值
Node child; // 子节点
Node next; // 同层兄弟节点
public Node(String value) {
this.value = value;
this.child = null;
this.next = null;
}
// 输出广义表
public void print() {
System.out.print(value);
if (child != null) {
System.out.print("(");
child.print();
System.out.print(")");
}
if (next != null) {
System.out.print(",");
next.print();
}
}
}
public class Main {
// 构造广义表
public static Node build(String s, int[] pos) {
Node node = null;
int len = s.length();
while (pos[0] < len) {
char c = s.charAt(pos[0]);
if (c == '(') {
pos[0]++;
Node child = build(s, pos);
if (node == null) {
node = child;
} else {
Node lastChild = node.child;
while (lastChild.next != null) {
lastChild = lastChild.next;
}
lastChild.next = child;
}
} else if (c == ')') {
pos[0]++;
return node;
} else if (c == ',') {
pos[0]++;
} else {
StringBuilder sb = new StringBuilder();
while (pos[0] < len && Character.isLetterOrDigit(s.charAt(pos[0]))) {
sb.append(s.charAt(pos[0]++));
}
Node n = new Node(sb.toString());
if (node == null) {
node = n;
} else {
Node lastChild = node.child;
while (lastChild != null && lastChild.next != null) {
lastChild = lastChild.next;
}
if (lastChild == null) {
node.child = n;
} else {
lastChild.next = n;
}
}
}
}
return node;
}
public static void main(String[] args) {
String str = "(a,(),c,(a,(c,d)),b)";
Node root = build(str, new int[]{0});
root.print();
}
}
```
以上代码可以完成广义表的存储与输出。如果还有其他问题,请继续提出。
相关推荐
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)