题解 | #两个链表生成相加链表#

两个链表生成相加链表

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

//三次反转列表即可
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

class Solution {
public:
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        //将链表反转
        auto new_head1 = new ListNode(-1);
        ListNode *next;
        while(head1){
            next = head1->next;
            head1->next = new_head1->next;
            new_head1->next = head1;
            head1 = next;
        }
        head1 = new_head1->next;//链表1反转结束
        new_head1->next = nullptr;
        while(head2){
            next = head2->next;
            head2->next = new_head1->next;
            new_head1->next = head2;
            head2 = next;
        }
        head2 = new_head1->next;//链表2反转结束
        int carry = 0;
        auto left = head1,right = head2;
        ListNode *prev = nullptr;
        while(left && right){
            int res = left->val + right->val + carry;
            if(res >= 10){
                carry = 1;
                left->val = res - 10;
            }else{
                carry = 0;
                left->val = res;
            }
            prev = left;
            left = left->next;
            right = right->next;
        }
        while(left){
            int res = left->val + carry;
            if(res >= 10){
                carry = 1;
                left->val = res - 10;
            }else{
                carry = 0;
                left->val = res;
                break;
            }
            prev = left;
            left = left->next;
        }
        if(carry == 1)
            prev->next = new ListNode(1);
        if(right)prev->next = right;
        while(right){
            int res = right->val + carry;
            if(res >= 10){
                carry = 1;
                right->val = res - 10;
            }else{
                carry = 0;
                right->val = res;
                break;
            }
            prev = right;
            right = right->next;
        }
        if(carry == 1)
            prev->next = new ListNode(1);
        //再翻转下
        new_head1->next = nullptr;
        while(head1){
            next = head1->next;
            head1->next = new_head1->next;
            new_head1->next = head1;
            head1 = next;
        }
        return new_head1->next;
    }
};
全部评论

相关推荐

不愿透露姓名的神秘牛友
11-26 15:46
已编辑
字节国际 电商后端 24k-35k
点赞 评论 收藏
分享
11-09 01:22
已编辑
东南大学 Java
高级特工穿山甲:羡慕,我秋招有家企业在茶馆组织线下面试,约我过去“喝茶详谈”😢结果我去了发现原来是人家喝茶我看着
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务