题解 | #牛牛的双链表求和#

牛牛的双链表求和

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;
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-30 11:32
点赞 评论 收藏
分享
07-28 16:37
门头沟学院 Java
哎,继续加油吧
ResourceUt...:能接到面试就已经是✌🏻了
腾讯一面2194人在聊
点赞 评论 收藏
分享
06-12 16:00
天津大学 Java
牛客30236098...:腾讯坏事做尽,终面挂是最破防的 上次被挂了后我连简历都不刷了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务