自定义Java链表仅打印头节点问题求助
Hey there! Let's figure out why your linked list only prints the head node—there are a few critical bugs in your code that are breaking the node linking logic. Let's break them down one by one:
1. LinkedNode Constructor Bug
First, look at your LinkedNode constructor:
public LinkedNode(Integer someData, LinkedNode next) { this.data = someData; this.next = null; // 这里是错误的! }
You're hardcoding this.next = null regardless of the next parameter passed in. This means every new node you create will have a null next pointer right off the bat, and any attempt to set a valid next reference gets undermined before you even start linking nodes.
Fix:
Replace the line with this.next = next; to respect the parameter you're passing:
public LinkedNode(Integer someData, LinkedNode next) { this.data = someData; this.next = next; }
2. addNode Method Logic is Broken
Your addNode method has incorrect logic that fails to properly link new nodes to the existing list. Let's walk through the issues:
- You're reassigning
myNodeto a new node every time the method runs, but never actually traversing the existing list to find the tail. - The
else if (myNode.getNext() == null)block setsmyNode.setNext(myNode), which creates a self-referential loop (the node points to itself) instead of linking to the new node. - None of your code actually attaches the new node to the end of the existing list.
Correct addNode Implementation:
The standard approach for adding to the end of a linked list is:
- Create the new node.
- If the list is empty (
head == null), set the new node as the head. - If the list isn't empty, traverse from the head until you reach the last node (where
current.getNext() == null), then set that last node's next to the new node.
Here's the fixed code:
public void addNode(Integer someData) { LinkedNode newNode = new LinkedNode(someData, null); // Create new node with null next if (head == null) { head = newNode; size++; } else { LinkedNode current = head; // Traverse to the last node while (current.getNext() != null) { current = current.getNext(); } // Attach new node to the end current.setNext(newNode); size++; } }
3. Verify printList Method
Your printList method is actually correct! Once you fix the constructor and addNode logic, it will properly traverse from the head through all linked nodes and print each element.
Testing the Fix
After making these changes, when you run readValues, it should correctly read all integers from the file, add each as a new node to the end of the list, and printList will output the full sequence like 40 --> X --> Y --> ... instead of just the head node.
内容的提问来源于stack exchange,提问作者ella_UW

