Java节点交换

我想在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 有什么提示吗????

elegantseven 回答:Java节点交换

看着您的对象,Node temp除了null之外没有指向任何其他对象。我不知道为什么您的编译器没有捕获到此错误,因为在空对象上使用点调用会引发nullpointerexception(例如temp.freq;此时将没有内容指向,也没有内部变量)。确保温度指向一个新节点,然后尝试从那里开始。

本文链接:https://www.f2er.com/3156722.html

大家都在问