【LeetCode】2. Add Two Numbers

Description:

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order 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.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

 

    就是两个链表相加,低位在前高位在后,相加后还有进位。这个题与另外做过的两道题67. Add Binary和21. Merge Two Sorted Lists。

    在Add Binary中也是做加法,在 Add Two Numbers中用到了和Add Binary中类似的while循环;Merge Two Sorted Lists是将两个排序好的链表合并成一个从大到小排列的链表,这道题用到了Merge Two Sorted Lists的新建节点。

   

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode prehead(0),*head = &prehead;
        int carry = 0;

        while(l1!=NULL || l2!=NULL || carry!=0){//当l1、l2、carry都空时再退出循环
            //carry与l1 l2 的值都相加,随后直接判断carry的值
            if(l1!=NULL) carry += l1->val; 
            if(l2!=NULL) carry += l2->val;
            
            if(carry>=10){
                head->next = new ListNode(carry%10);//这个地方纠结了很久,想不到怎么扩展链表,其实直接新建一个节点就好了
                carry = carry/10;
            }
            else if(carry<10){
                head->next = new ListNode(carry);
                carry = 0;
            }
            
            if(l1!=NULL) l1 = l1->next;//这个地方注意,当l1 l2 为空时,再让它们指向下一个节点会报错,因为已经指向空了。所以l1 l2指针下移时要有判定
            if(l2!=NULL) l2 = l2->next;
                                  
            head = head->next;
            
        }
        if(carry!=0) head->next = new ListNode(carry);
                
        return prehead.next;
    }
};

 

21. Merge Two Sorted Lists

 

67. Add Binary

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值