单链表赋值异常排查:LeetCode两数相加求解困境
LeetCode「Add Two Numbers」问题排查与修复
问题原因分析
1. char转int的错误
你看到的ch[i]和result.val数值不一致,是因为直接将char类型的字符赋值给int类型的val时,存储的是该字符的ASCII码值。比如字符'8'的ASCII码是56,'0'是48,'7'是55,所以输出会看到56、48、55这些数值,而非预期的8、0、7。
2. 返回空链表的原因
你把result初始化为l1,然后在循环中不断执行result = result.next,循环结束后result已经指向链表末尾的null,所以最终返回的是空链表。
3. 潜在的溢出问题
用Integer存储转换后的数值存在溢出风险,当链表表示的数字超过Integer最大值(2^31-1)时,会直接出错,不符合题目中“非负整数”的范围要求。
4. 链表复用的隐患
复用原链表l1的节点,如果两个输入链表长度不同,会出现节点数量不足或多余的情况,导致结果链表长度错误。
修复方案
方案一:修正字符转数字逻辑 + 新建结果链表
针对现有思路调整,解决核心问题:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { l1 = reverseList(l1); l2 = reverseList(l2); String str1 = returnListAsString(l1); String str2 = returnListAsString(l2); // 用Long避免Integer溢出 Long int1 = Long.valueOf(str1); Long int2 = Long.valueOf(str2); Long sum = int1 + int2; char[] ch = String.valueOf(sum).toCharArray(); // 新建结果链表,避免复用原节点的问题 ListNode dummy = new ListNode(0); ListNode curr = dummy; for (char c : ch) { // 将char转为对应整数:c - '0',利用ASCII码差值计算 curr.next = new ListNode(c - '0'); curr = curr.next; } // 返回结果链表的头节点(dummy.next) return dummy.next; } public ListNode reverseList(ListNode l1) { ListNode previous = null; ListNode curr = l1; ListNode next = null; while (curr != null) { next = curr.next; curr.next = previous; previous = curr; curr = next; } return previous; } public String returnListAsString(ListNode l1) { StringBuilder str1 = new StringBuilder(); while (l1 != null) { str1.append(l1.val); l1 = l1.next; } return str1.toString(); } }
方案二:推荐的逐位相加法(无溢出风险)
题目本身的链表是逆序存储数字的,无需反转链表,直接逐位相加并处理进位更高效,且完全避免溢出问题:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode dummy = new ListNode(0); ListNode curr = dummy; int carry = 0; while (l1 != null || l2 != null || carry != 0) { // 取当前位的数值,链表为空则取0 int val1 = (l1 != null) ? l1.val : 0; int val2 = (l2 != null) ? l2.val : 0; // 计算当前位总和与进位 int sum = val1 + val2 + carry; carry = sum / 10; // 当前位的数值为总和取余 curr.next = new ListNode(sum % 10); // 移动指针 curr = curr.next; if (l1 != null) l1 = l1.next; if (l2 != null) l2 = l2.next; } return dummy.next; } }
修复效果
输入[2,4,3]和[5,6,4]时,两种方案都能正确返回[8,0,7],其中方案二支持任意长度的非负整数相加,完全符合题目要求。
内容的提问来源于stack exchange,提问作者cluis92
相关产品推荐
相关产品推荐

