2 Add Two Numbers(Medium)

1.看题目的例子会容易混淆,弄不清楚哪边是低位,哪边是高位,实际上(2 -> 4 -> 4) + (5 -> 6 -> 4) = (7 -> 0 -> 9),即链表的头部是低位
2.这道题类似使用string存储的大整数相加,新增一个变量carry,代表进位,然后遍历链表即可
3.空间复杂度为O(1),时间复杂度为O(max(l1,l2)),即两个链表中最长的链表
4.注意(1)+(9->9->9->9->9->9)这样的情况,所以还是需要全部遍历一遍。

You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

AC代码:


/**
 * 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) {
        if(l1==NULL) return l2;
        else if(l2==NULL) return l1;
        
        ListNode* ans=l1;//以l1作为返回结果
        ListNode* preL1=l1;
        int c=0;//进位
        while(l1!=NULL&&l2!=NULL)
        {
            int sum=c+l1->val+l2->val;
            l1->val=sum%10;//求个位
            c=sum/10;//求进位
            
            preL1=l1;
            l1=l1->next;//指向下一个
            l2=l2->next;
        }
        if(l2!=NULL)//如果l2不为空,直接把l1接过去
        {
            preL1->next=l2;//当前的l1为空,所以要用前面的preL1指向l2
            l1=preL1->next;
        }

        
        while(l1!=NULL&&c!=0)
        {
            int sum=c+l1->val;
            l1->val=sum%10;
            c=sum/10;
            preL1=l1;
            l1=l1->next;
        }
        if(c!=0)
        {
            ListNode* tmp=new ListNode(c);
            preL1->next=tmp;
        }
        return ans;
    }
};

发表评论

电子邮件地址不会被公开。 必填项已用*标注