leetcode445

1、 Add Two Numbers II
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
Subscribe to see which companies asked this question.

思路一:将链表中的数字,分别放到两个容器内,这样就可以从后向前加啦~进位保存在变量CARRY中,余数就是相加后节点的 VAL,head指针不断向前

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    vector<int> nums1, nums2;
    while(l1) {
        nums1.push_back(l1->val);
        l1 = l1->next;
    }
    while(l2) {
        nums2.push_back(l2->val);
        l2 = l2->next;
    }

    int m = nums1.size(), n = nums2.size();
    int sum = 0, carry = 0;

    ListNode *head = nullptr, *p = nullptr;

    for(int i = m - 1, j = n - 1; i >= 0 || j >= 0 || carry > 0; i--, j--) {
        sum = carry;
        if(i >= 0) 
            sum += nums1[i];

        if(j >= 0)
            sum += nums2[j];

        carry = sum / 10;

        p = new ListNode(sum%10);
        p->next = head;
        head = p;
    }

    return head;
}

思路二:不能反转也可以考虑他们位数差,从前向后加,这样还要定义一个pre节点嗯~

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int length1=1, length2=1;
        ListNode* p=l1;
        ListNode* q=l2;
        while(p->next){
            length1++;
            p=p->next;
        }
        while(q->next){
            length2++;
            q=q->next;
        }
        int gap=length1-length2;
        int l=0;
        ListNode dummy(0);
        ListNode* cur=&dummy;
        ListNode* pre=&dummy;
        if(gap>0){
            p=l1;
            q=l2;
            pre->next=l1;
        }
        else{
            p=l2;
            q=l1;
            pre->next=l2;
        }


        while(l!=abs(gap)){
            p=p->next;
            pre=pre->next;
            l++;
        }
        while(p){
            int carry=(p->val+q->val)/10;//jinwei
            p->val=(p->val+q->val)%10;//yushu
            pre->val=pre->val+carry;
            pre=pre->next;
            p=p->next;
            q=q->next;
        }
        if(cur->val==0)
            return cur->next;
        else
            return cur;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值