题解 | #牛牛的双链表求和#
牛牛的双链表求和
https://www.nowcoder.com/practice/efb8a1fe3d1f439691e326326f8f8c95
#include <iostream> using namespace std; struct Node { int val; Node* next; Node(): val(0), next(nullptr) {} Node(int val): val(val), next(nullptr) {} Node(int val, Node* next): val(val), next(next) {} } ; void createList(Node* dummy, int n) { int i = 0; Node* node = dummy; while (i != n) { int d; cin >> d; node->next = new Node(d); node = node->next; i++; } } void addList(Node* dummy1, Node* dummy2) { Node* node1 = dummy1->next; Node* node2 = dummy2->next; while (node1 != nullptr && node2 != nullptr) { node2->val = node2->val + node1->val; node1 = node1->next; node2 = node2->next; } } void printList(Node* dummy) { Node* node = dummy->next; while (node != nullptr) { cout << node->val << " "; node = node->next; } } int main() { int n; cin >> n; Node* dummy1 = new Node(); Node* dummy2 = new Node(); createList(dummy1, n); createList(dummy2, n); addList(dummy1, dummy2); printList(dummy2); return 0; } // 64 位输出请用 printf("%lld")