Java语言怎么使用链表存储二叉树的连接矩阵的连接图呢?这个连接图的定义在Java里的实现是什么
效果如图
代码及分析
import java.util.LinkedList;
// 二叉树节点类
class BinaryTreeNode {
int value;
BinaryTreeNode left;
BinaryTreeNode right;
public BinaryTreeNode(int value) {
this.value = value;
}
}
// 连接矩阵类
class ConnectionMatrix {
LinkedList<BinaryTreeNode> connections;
public ConnectionMatrix() {
connections = new LinkedList<>();
}
public void addConnection(BinaryTreeNode node) {
connections.add(node);
}
}
public class Main {
public static void main(String[] args) {
// 构建示例二叉树
BinaryTreeNode root = new BinaryTreeNode(1);
BinaryTreeNode node2 = new BinaryTreeNode(2);
BinaryTreeNode node3 = new BinaryTreeNode(3);
BinaryTreeNode node4 = new BinaryTreeNode(4);
BinaryTreeNode node5 = new BinaryTreeNode(5);
root.left = node2;
root.right = node3;
node2.left = node4;
node2.right = node5;
// 创建连接矩阵
ConnectionMatrix matrix = new ConnectionMatrix();
// 添加节点连接关系到连接矩阵
matrix.addConnection(root);
matrix.addConnection(node2);
matrix.addConnection(node3);
matrix.addConnection(node4);
matrix.addConnection(node5);
// 打印连接矩阵中的节点值
for (BinaryTreeNode node : matrix.connections) {
System.out.println(node.value);
}
}
}
不知道你这个问题是否已经解决, 如果还没有解决的话:public static void main(String[] args) {
Student s1 = new Student("张三");
Student s2 = new Student("李四");
swap(s1, s2);
System.out.println("s1: " + s1.getName());
System.out.println("s2: " + s2.getName());
}
// 交换方法
public static void swap(Student a, Student b) {
Student temp = a;
a = b;
b = temp;
System.out.println("a: " + a.getName());
System.out.println("b: " + b.getName());
}
结果:
a: 李四
b: 张三
s1: 张三
s2: 李四
解析:
如图所示,方法并没有改变存储在变量 s1 和 s2 中的对象引用指向。 而只是把拷贝副本的指向进行了交换,原实参s1、s2并未改变。此时可能有人会说,“我可以通过 a 修改 student 1 的值,s1指向的对象不就变了,不就是传递引用,改变了实参值吗?” 这是Java对象是引用传递支持者最大的举证,但有一个很大的误区。即我们传的是对象引用,而我们改正的是什么,是对象,这本就是两个东西,你并没有修改你传的实参值(对象引用)的指向,而在C++中引用参数标有 & 符号。 可以轻松地实现void swap(double& a, double& b)方法或 void swap(Student& a, Student& b) 方法实现修改它们的实参值(引用参数)的目的,既通过交换形参,而交换实参,因为它们本质用的是同一块内存。