题解 | 链表相加(二)_c++

链表相加(二)

https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

#include<iostream>
using namespace std;
#include<bits/stdc++.h>
class Solution {
  public:
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        if (!head1 || !head2) return !head1 ? head2 : head1;
        function<ListNode*(ListNode*)> reverse = [&](ListNode * node)->ListNode* {
            ListNode* pre = nullptr, * last = node;
            while (last) {
                ListNode* tmp = last->next;
                last->next = pre;
                pre = last;
                last = tmp;
            }
            return pre;
        };
        ListNode* l1 = reverse(head1), * l2 = reverse(head2);
        ListNode* root = new ListNode(0),* cur = root;
        int jinwei = 0;
        while (l1 || l2 || jinwei) {
            int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + jinwei;
            jinwei = sum / 10;
            cur->next = new ListNode(sum % 10);
            cur = cur->next;
            if(l1) l1 = l1->next;
            if(l2) l2 = l2->next;
        }
        return reverse(root->next);
    }









};

全部评论

相关推荐

04-13 11:19
门头沟学院 HTML5
NullPointe...:27实习的都快结束了吧
点赞 评论 收藏
分享
04-08 16:35
门头沟学院 Java
站队站对牛:实在是恶心的公司
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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