给出上述题目的C++代码
时间: 2024-04-16 10:28:12 浏览: 19
下面是一个示例的C++代码,用于将两个逆序存储的非负整数链表相加并返回结果链表:
```cpp
#include <iostream>
#include <vector>
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* dummy = new ListNode(0);
ListNode* curr = dummy;
int carry = 0;
while (l1 || l2 || carry) {
int sum = carry;
if (l1) {
sum += l1->val;
l1 = l1->next;
}
if (l2) {
sum += l2->val;
l2 = l2->next;
}
carry = sum / 10;
ListNode* newNode = new ListNode(sum % 10);
curr->next = newNode;
curr = curr->next;
}
return dummy->next;
}
void printList(ListNode* head) {
while (head) {
std::cout << head->val << " ";
head = head->next;
}
std::cout << std::endl;
}
int main() {
// Create two example lists: 2->4->3 and 5->6->4
ListNode* l1 = new ListNode(2);
l1->next = new ListNode(4);
l1->next->next = new ListNode(3);
ListNode* l2 = new ListNode(5);
l2->next = new ListNode(6);
l2->next->next = new ListNode(4);
// Add the two lists
ListNode* result = addTwoNumbers(l1, l2);
// Print the result
printList(result);
return 0;
}
```
运行上述代码,输出为:
```
7 0 8
```
表示相加后的链表为:7->0->8。