Python实现两链表对应元素求和时出现无限循环、迭代异常问题
问题根因
- 无限循环的触发点在
two_sum函数的链表指针移动逻辑,原代码写法错误:
l1 = l1.next_node if l1.next_node else l1 l2 = l2.next_node if l2.next_node else l2
当链表遍历到尾部节点时,l1.next_node为None,按照当前逻辑会将l1赋值为自身,永远不会变为None。而循环退出条件为l1 is not None or l2 is not None,因此循环会持续执行无法退出。
修复方案
- 修正指针移动逻辑:只要当前节点不为空,就将指针移动到下一个节点,否则保持
None状态,保证遍历到链表尾部时指针会正确置空,触发循环退出。 - 正确的指针移动代码:
l1 = l1.next_node if l1 else None l2 = l2.next_node if l2 else None
- 额外优化:原代码中变量名
sum与Python内置函数sum重名,建议修改为其他变量名避免潜在冲突。
修复后完整求和代码
def two_sum(list1: LinkedList, list2: LinkedList) -> LinkedList: l1 = list1.head l2 = list2.head res_list = LinkedList() carry = 0 while l1 is not None or l2 is not None: x = l1.data if l1 else 0 y = l2.data if l2 else 0 sum_val = carry + x + y res_list.add_last(Node(sum_val % 10)) carry = carry // 10 # 修正后的指针移动逻辑 l1 = l1.next_node if l1 else None l2 = l2.next_node if l2 else None if carry > 0: res_list.add_last(Node(carry)) return res_list
内容的提问来源于stack exchange,提问作者Major Mail
相关产品推荐
相关产品推荐

