请教各位,这个样例输入和输出得怎么写啊? (5->6->4)
原题:
两组三位整数数据链表,用结构体 ListNode 表示,每个节点只放一位数字:
struct ListNode {
int val;
struct ListNode *next;
};
要求建立如下例的链表,并利用链表实现加法运算。
【样例输入】
(2->4->3)+(5->6->4) //说明:表示 342+465
(5->6->7)+(7->8->9)
【样例输出】
(7->0->8)
(2->5->7->1)
请教各位,这个样例输入和输出得怎么写啊? (5->6->4)
原题:
两组三位整数数据链表,用结构体 ListNode 表示,每个节点只放一位数字:
struct ListNode {
int val;
struct ListNode *next;
};
要求建立如下例的链表,并利用链表实现加法运算。
【样例输入】
(2->4->3)+(5->6->4) //说明:表示 342+465
(5->6->7)+(7->8->9)
【样例输出】
(7->0->8)
(2->5->7->1)
引自免费微信小程序:皆我百晓生
为了解决这个问题,我们首先需要定义ListNode
结构体,然后编写函数来处理链表的创建、相加以及结果的输出。下面是一个可能的实现方案:
#include <iostream>
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
// Function to add two numbers represented by linked lists
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode dummyHead(0);
ListNode* p = &dummyHead;
int carry = 0;
while (l1 != NULL || l2 != NULL || carry != 0) {
int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry;
carry = sum / 10;
p->next = new ListNode(sum % 10);
p = p->next;
if (l1) l1 = l1->next;
if (l2) l2 = l2->next;
}
return dummyHead.next;
}
// Function to create a linked list from an array of digits
ListNode* createLinkedList(const std::vector<int>& digits) {
ListNode dummyHead(0);
ListNode* p = &dummyHead;
for (int digit : digits) {
p->next = new ListNode(digit);
p = p->next;
}
return dummyHead.next;
}
// Function to print the linked list
void printList(ListNode* head) {
while (head) {
std::cout << head->val;
if (head->next) std::cout << "->";
head = head->next;
}
std::cout << std::endl;
}
int main() {
// Example input
ListNode* l1 = createLinkedList({2, 4, 3});
ListNode* l2 = createLinkedList({5, 6, 4});
// Add the two numbers
ListNode* result = addTwoNumbers(l1, l2);
// Print the result
printList(result);
// Clean up memory
while (l1) {
ListNode* temp = l1;
l1 = l1->next;
delete temp;
}
while (l2) {
ListNode* temp = l2;
l2 = l2->next;
delete temp;
}
while (result) {
ListNode* temp = result;
result = result->next;
delete temp;
}
return 0;
}
这段代码首先定义了一个ListNode
结构体用于链表的节点。接着实现了addTwoNumbers
函数,它接受两个链表作为参数,返回它们相加的结果。createLinkedList
函数用于从一个整数数组创建链表,而printList
函数则用于打印链表。在main
函数中,我们创建了两个链表,调用了addTwoNumbers
函数进行加法操作,并打印了结果。最后,我们清理了所有分配的内存,防止内存泄漏。
这样,你就能够按照题目要求的格式处理链表的输入和输出了。