我正在尝试添加两个数字(以链表的形式以相反的顺序表示)。我有C ++的解决方案
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
bool carry = 0;
ListNode *head1 = l1;
ListNode *head2 = l2;
ListNode *head = nullptr;
ListNode *curr = nullptr;
while (head1 || head2 || carry) {
// get value
int val = (head1 ? head1->val : 0) +
(head2 ? head2->val : 0) + carry;
curr = new ListNode(val % 10);
if (!head) head = curr;
curr = curr->next;
head1 = head1 ? head1->next : nullptr;
head2 = head2 ? head2->next : nullptr;
carry = val / 10;
}
return head;
}
};
由于某种原因,这只会返回长度为1的链表。此初始化头不应该在第一次使用curr时使用,然后curr才能继续正确建立列表吗?
答案 0 :(得分:0)
如Ian4264和JaMiT所述,第一次进入循环时,将创建一个新节点,并使其指向curr
。此后,立即将curr
设置为curr->next
,它指向某个任意位置。您永远不会将curr->next
指向该位置进行进一步分配。
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
bool carry = 0;
ListNode *head1 = l1;
ListNode *head2 = l2;
ListNode *head = nullptr;
ListNode *curr = nullptr;
while (head1 || head2 || carry) {
// get value
int val = (head1 ? head1->val : 0) +
(head2 ? head2->val : 0) + carry;
if (!curr){
//first time around the loop (curr is nullptr)
//set curr to point to a new node
curr = new ListNode(val % 10);
}
else {
//if current was pointing to some node already, then
//its's next is set to point to the new allocation and curr
//is set to the last node (just allocated) - and thus
//current
curr->next = new ListNode(val % 10);
curr = curr->next;
}
if (!head) head = curr;
head1 = head1 ? head1->next : nullptr;
head2 = head2 ? head2->next : nullptr;
carry = val / 10;
}
return head;
}
};