我想在java中交换2个节点,这是我的节点类
public class Node {
int freq;
Node left,right,parent;
}
我想交换树中的 2 个节点
public void swap(Node a, Node b){
Node temp;
temp.freq=a.freq;
temp.parent=a.parent;
temp.left=a.left;
temp.right= a.right;
a.freq=b.freq;
a.left=b.left;
a.right=b.right;
a.parent=b.parent;
b.freq=temp.freq;
b.left=temp.left;
b.right=temp.right;
b.parent=temp.parent;
}
但我发现两个节点的父节点都变成了 b.parent 有什么提示吗???
最佳答案
查看您的对象,Node temp 不指向除 null 之外的任何内容。我不知道为什么你的编译器没有捕获这个错误,因为对空对象使用点调用会抛出空指针异常(例如 temp.freq;此时它没有任何可指向的内容,也没有内部变量)。确保 temp 指向一个新节点并尝试从那里开始。
关于Java 节点交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58718663/