这是一个解释我的麻烦的程序。 我有一个插入函数,它既有当前节点又有父节点作为参数。 对于第一次插入,我在列表中插入5,root基本上成为带有5的节点。对于第二次插入,我将2插入到列表中,但这次应该将其父节点设置为null。
当我在两次插入后打印时,它应该显示
This node's value is 5但相反,它仍然显示父级的下一个仍然链接到第二个节点。
This node's value is 5 This node's value is 2为什么我的parent.next = null不生效? 有没有办法来解决这个问题? 我有一个实现,需要能够修改父。
public class LinkedList{ private class Node{ int value; Node next; } private Node root; public LinkedList(){ root = null; } public void insert(int value){ root = insert(root, root, value); } public Node insert(Node node, Node parent, int value){ if(root == null){ node = new Node(); node.value = value; }else if(node == null){ node = new Node(); node.value = value; parent.next = null; }else{ node.next = insert(node.next, node, value); } return node; } public void printAll(){ printAll(root); } public void printAll(Node node){ Node traverse = node; while(traverse != null){ System.out.println("This node's value is " + traverse.value); traverse = traverse.next; } } public static void main(String[] args){ LinkedList myList = new LinkedList(); myList.insert(5); myList.insert(2); myList.printAll(); } }Here is a program explaining my troubles. I have an insert function that has both the current node and the parent node as parameters. For the first insertion, I insert 5 into the list, the root basically becomes the Node with 5. For the second insertion, I insert 2 into the list, but this time it is supposed to set its parent node's next to null.
When I print after both insertions, it should display
This node's value is 5But instead, it still shows that the parent's next is still link to the 2nd node.
This node's value is 5 This node's value is 2Why doesn't my parent.next = null take effect? Is there a way to fix this? I have an implementation that requires the ability to modify the parent.
最满意答案
您在插入第一个节点时传递null,null。 然后,将返回哪个节点公共Node insert(Node node, Node parent, int value) 。 再看看
public void insert(int value){ root = insert(root, root, value); }You are passing null,null when inserting the first node. Then, which node public Node insert(Node node, Node parent, int value) will return. Take a look again
public void insert(int value){ root = insert(root, root, value); }更多推荐
发布评论