/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { /** * @param l1: the first list * @param l2: the second list * @return: the sum list of l1 and l2 */ public ListNode addLists(ListNode l1, ListNode l2) { // write your code here int digit1 = l1.val; int digit2 = l2.val; int digitS = (digit1 + digit2) % 10; int c = (digit1 + digit2) / 10; l1 = l1.next; l2 = l2.next; ListNode sum = new ListNode(digitS); ListNode head = sum; while (!(l1 == null && l2 == null && c == 0)){ digit1 = l1 == null ? 0 : l1.val; digit2 = l2 == null ? 0 : l2.val; digitS = (digit1 + digit2 + c) % 10; c = (digit1 + digit2 + c) / 10; l1 = l1 == null ? l1 : l1.next; l2 = l2 == null ? l2 : l2.next; sum.next = new ListNode(digitS); sum = sum.next; } return head; } }
1. 小心处理l1和l2其中有一个先null了的情况,可以digit1 = l1 == null ? 0 : l1.val;
2. 还有小心l1后移的情况,如果l1已经是null了,那就不能后移了,所以要l1 = l1 == null ? l1 : l1.next;
3. 小心后面每次加的时候要多加个c;
时间: 2024-10-08 21:14:28