讨论/题目交流/想请教一下 我这题 哪里出问题了/
想请教一下 我这题 哪里出问题了

image.png
image.png
image.png

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(-1);
        ListNode curr = dummy;
        int index = 0;
        while (l1 != null && l2 != null) {
            int val1 = (l1 != null) ? l1.val : 0;
            int val2 = (l2 != null) ? l2.val : 0;
            int sum = val1 + val2 + index;
            index = sum/10;
            curr.next = new ListNode(sum%10);
            curr = curr.next;
            if (l1!=null) l1 = l1.next;
            if (l2!=null) l2 = l2.next;
        }
        if (index==1){
            curr.next = new ListNode(index);
        }
        return dummy.next;
    }
}


展开讨论
心成发起于 2019-10-07
最近编辑于 2019-10-07

while (l1 != null && l2 != null) 改成 while (l1 != null || l2 != null)

1
展开全部 3 讨论