java - 我删除具有 X 年龄值的特定节点的删除方法将不起作用

标签 java

这是我的代码,请仅引用主要方法和删除方法,其他方法只是为了显示完整的程序。我听说Java将方法参数作为按值传递,这就是问题所在,并且对象的属性是按引用传递。

所以基本上我可以更改Node.age,因为age是一个属性,但我不能使Node等于Node = Node.next?我已经从事这个工作有一段时间了,只是想学习如何进行不同的操作,并且一直停留在这个问题上。 if 语句执行完毕,但是 headNode 并不像我希望的那样等同于 headNode.next:

public class Node {
    int age;
    Node next;
    Node previous;

    public static void main (String [] args) {
        Node firstNode = new Node(18);
        Node t = firstNode;

        Node randomFatNode = new Node();

        for(int i = 0; i < 30; i += 3) {
            Node tempNode = new Node(i + 21);
            firstNode.next = tempNode;
            tempNode.previous = firstNode;
            firstNode = tempNode;
        }

        Node tailNode = firstNode;

        firstNode = t;

        traverseForward(firstNode);
        //Prints out: Traversal Forward -> 18 -> 21 -> 24 -> 27 -> 30 -> 33 -> 36 -> 39 -> 42 -> 45 -> 48 -> null


        deleteNode(firstNode, 18); //Does not delete the first node, which has the age of 18.

        traverseForward(firstNode);
        //Prints out: Traversal Forward -> 18 -> 21 -> 24 -> 27 -> 30 -> 33 -> 36 -> 39 -> 42 -> 45 -> 48 -> null
    }

    public Node() {
        this.age = 20;
        this.next = null;
        this.previous = null;
    }

    public Node(int inputAge) {
        this.age = inputAge;
        this.next = null;
        this.previous = null;
    }

    public static void traverseForward(Node headNode) {
        System.out.print("Traversal Forward -> ");
        Node useThisForTestNode = headNode;
        while(useThisForTestNode != null) {
            System.out.print(useThisForTestNode.age + " -> ");
            useThisForTestNode = useThisForTestNode.next;
        }
        System.out.print("null ");
        System.out.println();
    }

    public static void deleteNode(Node headNode, int keyToDelete) {
        Node temp = headNode;
        if(temp != null && temp.age == keyToDelete)  {
            headNode = headNode.next;
            System.out.println("TEST");
            //Printed out TEST to see if if statement went through. It did, but the node in the linked list remained unchanged.
        }
    }

    // Other methods
}

最佳答案

您需要将firstNode作为类字段。

关于java - 我删除具有 X 年龄值的特定节点的删除方法将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45778785/

相关文章:

java - 将显式 Intent 从 ViewPagerAdapter 传递给 fragment

Java ComboBox 如何填充点击添加项目不起作用

java - 如何确定 Netbeans 正在执行哪个命令来运行项目?

java - 用于 Java 开发的 Linux 发行版

java - 我正在为我的应用程序构建 googlemap 跟踪,现在我被困了五天多了,我认为,,简单''问题

java - REST Web 服务中@Consumes 的默认值是什么?

java - 收集后从 Spark Map 操作中获取 null 图形字段

java - JPA 引用 : are there any guarantees related to field contents?

java - JFrame 重绘();错误

java - 错误: Could not find or load main class Mac Eclipse