我正在尝试添加两个数字(表示为链接列表,数字顺序相反(。我有一个解决方案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 的链接列表。这不应该第一次初始化 head 以 curr 吗,然后 curr 将继续正确构建列表?
正如 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;
}
};