题目

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.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
My Solutation

/**
 * 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 *l3=new ListNode(0),*result,*last;
        int bit=0,flag=0,sum=0;
        if(l3==NULL)
            return l3;
         result=l3;
        while((l1!=NULL)||(l2!=NULL))
        {
            sum=0;
            if((l1!=NULL)&&(l2!=NULL))
            {
                sum=l1->val+l2->val;
                l1=l1->next;
                l2=l2->next;
            }else if(l1==NULL)
            {
                sum=l2->val;
                l2=l2->next;
            }else if(l2==NULL)
            {
                sum=l1->val;
                l1=l1->next;
            }
            sum+=bit;
            bit=sum/10;
            l3->val=sum%10;
            l3->next=new ListNode(0);
            last=l3;
            l3=l3->next;
        }
        if(bit)
            {
                l3->val=bit;
               l3->next=NULL;
            }
        else
            {
                last->next=NULL;
                delete l3;
            }
        return result;
    }
};
  • 解决思路:幸好题目的位数是逆位的,我设置一个bit位用来存放是否有低位到高位的进位,循环两个链表,位数相加赋值给sum,bit是通过sum取余得到的,整个解决方案很简单。

  • 时间复杂度:O(n+m)

  • 空间复杂度:O(n)