[英]Adding two numbers as linked lists
我正在嘗試添加兩個數字(以相反順序的數字表示為鏈表)。 我在 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;
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.