首页 > 代码库 > [LeetCode]2. Add Two Numbers

[LeetCode]2. Add Two Numbers

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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
 
给你两个非空链表表示两个非负整数。它们的位数被反向排序了,并且每个节点表示每位,对这两个数求和,并返回一个像这样的链表。
你可以假设这两个数不会存在最高位出现0的情况,除了0这个数本身。
 
思路:按照计算习惯,我们都是从各位开始计算,用链表反序表示,正好就从表头开始计算,只不过要注意进位。
/**
 * 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 prevHead(0),*p=&prevHead;
        int extra=0;
        while(l1||l2||extra){                  //如果l1 l2 extra有一个存在有效值 那就得继续计算
            int sum=(l1?l1->val:0)+(l2?l2->val:0)+extra;
            
            p->next=new ListNode(sum%10);       //当前位上的值
            extra=sum/10;                       //进位
            
            p=p->next;
            l1=l1?l1->next:l1;
            l2=l2?l2->next:l2;
        }
        return prevHead.next;
    }
};

 

 

[LeetCode]2. Add Two Numbers