链表逆序相加问题求助:LeetCode题目输出异常
Hey there! Let's dig into why your code is only returning [7] instead of the expected [7,0,8] for this LeetCode problem. This is a classic linked list pitfall, so let's break down the most likely issues and fix them together.
Common Causes for Incomplete Output
1. Your Loop Stops Too Early
The most probable issue is that your loop only processes the first pair of nodes and exits immediately. Remember, you need to keep iterating as long as either linked list has remaining nodes, or there's a carry-over left to process.
For example, if your loop condition is something like while l1 is not None and l2 is not None, it will stop after the first node (since both l1 and l2 have nodes there), but it won't handle the remaining nodes in either list or any leftover carry.
2. You're Not Handling Carry-Over Correctly
Let's walk through the example step by step:
- First nodes: 2 + 5 = 7 (no carry)
- Second nodes: 4 + 6 = 10 (carry = 1, current digit is 0)
- Third nodes: 3 + 4 + 1 (carry) = 8 (no carry left)
If you don't track and carry over this 1 to the next iteration, you'll never compute the second and third digits of the result.
3. You're Not Building the Result List Properly
Another common mistake is failing to link new nodes to your result list, or not moving the result pointer forward after creating a new node. For example, if you only create the first result node and never update the pointer to add subsequent nodes, your list will only contain that first 7.
Example of a Correct Solution
Here's a working implementation (in Python) that addresses all these issues:
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def addTwoNumbers(l1, l2): # Dummy head makes it easier to build the result list without edge cases dummy_head = ListNode(0) current = dummy_head carry = 0 # Keep looping until both lists are exhausted AND no carry is left while l1 is not None or l2 is not None or carry != 0: # Get values (0 if the list is already exhausted) val1 = l1.val if l1 else 0 val2 = l2.val if l2 else 0 # Calculate total and update carry total = val1 + val2 + carry carry = total // 10 current_digit = total % 10 # Add new node to result list current.next = ListNode(current_digit) current = current.next # Move pointers forward if possible if l1: l1 = l1.next if l2: l2 = l2.next # Return the actual result (skip the dummy head) return dummy_head.next
How to Fix Your Code
Check these key parts of your code:
- Loop condition: Make sure it includes cases where one list is empty but the other isn't, or when there's a carry left after both lists are done.
- Carry handling: Ensure you're adding the carry to each sum, updating it each iteration, and not discarding it after the first step.
- Result list construction: Verify that you're linking each new node to the result and moving the result pointer forward each time.
内容的提问来源于stack exchange,提问作者user1238097

