LeetCode - 2. Add Two Numbers

LeetCode - 2. Add Two Numbers

题目:

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

题目大意:

给你两个链表,链表中存放的是非负数。链表中的数字是逆序存放,并且每个节点都只有一位数字。求讲这两个数字相加得到的链表

考点:

  1. 链表操作
  2. n位数相加,考虑进位
  3. 两个数相加,可能位数不同
  4. 如果最后还有一个进位,需要再添加一个节点保存进位数字

代码:

/**
 * 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;
        if(l2 == NULL) return l1;
        ListNode* p1 = l1;
        ListNode* p2 = l2;
        ListNode* result = NULL;
        ListNode* pResult = NULL;

        int jinwei = 0;
        while(p1 !=NULL || p2 != NULL)
        {
            int num1 = (p1 == NULL ? 0 : p1->val);
            int num2 = (p2 == NULL ? 0 : p2->val);

            int val = (num1 + num2 + jinwei) % 10;
            jinwei = (num1 + num2 + jinwei) / 10;
            if(result == NULL)
            {
                result = new ListNode(val);
                pResult = result;
            }
            else
            {
                ListNode* temp = new ListNode(val);
                pResult->next = temp;
                pResult = pResult->next;
            }

            p1 = (p1 == NULL? NULL: p1->next);
            p2 = (p2 == NULL? NULL: p2->next);
        }
        if( jinwei > 0){
            ListNode* temp = new ListNode(jinwei);
            pResult->next = temp;
            pResult = temp->next;
        }
        return result;
    }
};

你可能感兴趣的:(LeetCode - 2. Add Two Numbers)