leetcode-两个链表生成相加链表-76

题目要求
  假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。
给定两个这种链表,请生成代表两个整数相加值的结果链表。
例如:链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。
解析
1.将链表翻转
2.将链表相加,如果大于10,则有进位,如果链表A,链表B,进位中任何一个有值,都需再往前执行一次
3.将链表翻转回来
代码实现

/**
 * 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* reverseList(ListNode* head)
    {
        if(head == nullptr || head->next == nullptr)
            return head;
        ListNode* prev = head;
        ListNode* cur = prev->next;
        ListNode* next = cur->next;
        prev->next = nullptr;
        cur->next = prev;
        while(next != nullptr)
        {
            prev = cur;
            cur = next;
            next = next->next;
            cur->next = prev;
        }
        return cur;
    }

    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        if(head1 == nullptr)
            return head2;
        if(head2 == nullptr)
            return head1;
        
        ListNode* l1 = reverseList(head1);
        ListNode* l2 = reverseList(head2);
        ListNode* ans = new ListNode(0);
        ListNode* cur = ans;
    
        int carry = 0;//进位
        while(l1 || l2 || carry)
        {
            int x = l1 ? l1->val : 0;
            int y = l2 ? l2->val : 0;
            int sum  = x + y + carry;
            carry = sum / 10;;
            sum %= 10;
       		cur->next = new ListNode(sum);//val = sum
 	           cur = cur->next;
            if(l1)
                l1 = l1->next;
            if(l2)
                l2 = l2->next;
        }
        ans = ans->next;
        ans = reverseList(ans);
        return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天津 唐秙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值