关于 LeetCode 2 和链表的问题

Question about LeetCode 2 and linked list

最近在学习linked list,卡在了LeetCode No.2。我知道 linked 列表可以有一个没有任何数据的头部,但有一个对列表中包含数据的第一个节点的引用(link)。在这种情况下,l1 和 l2 似乎都没有这种头?还有,方法return head.next不是head,那结果是不是也是没有这种head的list呢?那么在什么情况下我们应该使用上面提到的头部列表呢?

解决方法如下:

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int carry = 0;
        ListNode head = new ListNode(0), p = head;
        while (l1 != null || l2 != null || carry != 0) {
            int sum = carry;
            if (l1 != null) { sum += l1.val; l1 = l1.next; } 
            if (l2 != null) { sum += l2.val; l2 = l2.next; }
            p.next = new ListNode(sum % 10);
            p = p.next;
            carry = sum / 10;
        }
        return head.next;
    }
}

I know that linked list can have a head without any data but a reference(link) to the first node containing data in the list.

这其实不是正常的链表存储方式。 “没有任何数据的头部”可能会产生误导,因为不清楚该节点是否没有数据。如果你要 return 这样一个列表,Leet Code 不会将第一个节点与其他节点区别开来:它的数据将被认为是相关的。

it seems both l1 and l2 doesn't have this kind of head?

没错。

does that mean that the result is also a list without this kind of head?

是的,这就是 Leet Code 所期望的。

Then in which case shall we use a list with a head mentioned above?

使用它并不是绝对的要求,但它使代码更容易一些。它是一个临时虚拟节点,最后没有 returned。

下面是当您不创建额外节点时代码的样子:

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int carry = 0;
        ListNode head = null, p = null;
        while (l1 != null || l2 != null || carry != 0) {
            int sum = carry;
            if (l1 != null) { sum += l1.val; l1 = l1.next; } 
            if (l2 != null) { sum += l2.val; l2 = l2.next; }
            ListNode node = new ListNode(sum % 10);
            if (head == null) {
                head = node;
            } else {
                p.next = node;
            }
            p = node;
            carry = sum / 10;
        }
        return head;
    }
}

请注意,现在循环体必须检查它是哪种情况:这是第一个节点吗?然后 head 必须引用它。如果不是,则前一个节点的 next 属性必须引用它。遗憾的是,在 each 迭代中执行此检查,而实际上只在第一次需要。虚拟节点的使用使这一点变得不必要。