假设有两个链表,分别表示非负整数 A 和 B,且每个节点只能存储一位数字。我们需要计算这两个链表的和,并以相同形式返回一个表示和的链表。
下面是一个示例的 C++ 代码实现:
#include <iostream>
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode dummy(0);
ListNode* curr = &dummy; // 当前节点
int carry = 0; // 进位
while (l1 || l2 || carry) {
int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry;
carry = sum / 10; // 计算进位
curr->next = new ListNode(sum % 10); // 创建新节点存储当前位的数字
curr = curr->next;
if (l1)
l1 = l1->next;
if (l2)
l2 = l2->next;
}
return dummy.next;
}
// 创建链表
ListNode* createList(const std::string& numStr) {
ListNode dummy(0);
ListNode* curr = &dummy;
for (char c : numStr) {
int digit = c - '0';
curr->next = new ListNode(digit);
curr = curr->next;
}
return dummy.next;
}
// 打印链表
void printList(ListNode* head) {
while (head != nullptr) {
std::cout << head->val;
head = head->next;
}
std::cout << std::endl;
}
int main() {
// 创建两个链表
ListNode* l1 = createList("123");
ListNode* l2 = createList("456");
// 计算两个链表的和
ListNode* sum = addTwoNumbers(l1, l2);
// 打印结果
printList(sum);
return 0;
}
以上代码中,addTwoNumbers()
函数用于计算两个链表的和。它通过遍历两个链表,将对应位置上的数字相加,并考虑进位。如果某一链表较短,则可以将缺少的高位看作是0。
createList()
函数用于根据给定的字符串创建一个表示非负整数的链表。
printList()
函数用于打印链表中的每个节点值。
你可以根据自己的需求进行调整和扩展。希望对你有所帮助!
内容由零声教学AI助手提供,问题来源于学员提问