题解 | #牛牛的双链表求和#
牛牛的双链表求和
https://www.nowcoder.com/practice/efb8a1fe3d1f439691e326326f8f8c95
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
int main() {
int n;
cin >> n;
Node* a_head = new Node;
Node* b_head = new Node;
//构造链表a
Node* p = a_head;
for (int i = 0; i < n; i++) {
p->next = new Node;
cin >> p->next->data;
p = p->next;
}
//构造链表b
Node* q = b_head;
for (int i = 0; i < n; i++) {
q->next = new Node;
cin >> q->next->data;
q = q->next;
}
//把链表a中的值加到链表b中
p = a_head->next;
q = b_head->next;
for (int i = 0; i < n; i++) {
q->data += p->data;
p = p->next;
q = q->next;
}
//输出加和后的链表
q = b_head->next;
while (q) {
cout << q->data << ' ';
q = q->next;
}
return 0;
}
SHEIN希音公司福利 278人发布