145 条题解
-
-3
这里估计大部分都是写了c++有一定基础的,那么我就用链表实现a+b问题吧
#include <iostream> 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 *current = 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; sum = sum % 10; current->next = new ListNode(sum); current = current->next; } return dummy->next; } ListNode *createLinkedList(int arr[], int n) { if (n == 0) { return nullptr; } ListNode *head = new ListNode(arr[0]); ListNode *current = head; for (int i = 1; i < n; i++) { current->next = new ListNode(arr[i]); current = current->next; } return head; } void printLinkedList(ListNode *head) { ListNode *current = head; while (current) { std::cout << current->val << " "; current = current->next; } std::cout << std::endl; } int main() { int arr1[1]; int arr2[1]; std::cin >> arr1[0]; std::cin >> arr2[0]; int n1 = sizeof(arr1) / sizeof(arr1[0]); int n2 = sizeof(arr2) / sizeof(arr2[0]); ListNode *l1 = createLinkedList(arr1, n1); ListNode *l2 = createLinkedList(arr2, n2); ListNode *sum = addTwoNumbers(l1, l2); printLinkedList(sum); return 0; }
信息
- ID
- 56
- 时间
- 1000ms
- 内存
- 1024MiB
- 难度
- 1
- 标签
- 递交数
- 9043
- 已通过
- 4027
- 上传者