一开始我的思路是先分别获取两个数字,再相加后构造新链表,这样的方法虽然效率低但是可能可以实现(老菜鸡了),但是发现后面的示例的位数超过了Integer.MAX_VALUE,只能用long然后强转……看了优秀的题解之后发现人家是这样做的,直接使用两个链表的单个值进行相加,但是需要取余(题目要求每个值都必须是个位数),最后如果表示十位的变量不为0,还需要补一个1的结点。
/** * 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 pre = new ListNode(0); ListNode cur = pre; int carry = 0; while(l1 != null || l2 != null) { int x = l1 == null ? 0 : l1.val; int y = l2 == null ? 0 : l2.val; int sum = x + y + carry; carry = sum / 10; sum = sum % 10; cur.next = new ListNode(sum); cur = cur.next; if(l1 != null) l1 = l1.next; if(l2 != null) l2 = l2.next; } if(carry == 1) { cur.next = new ListNode(carry); } return pre.next; } }