LeetCodeDay41 —— 两数相加★☆

2. 两数相加

描述
  • 给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
  • 你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例
  输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
  输出:7 -> 0 -> 8
  原因:342 + 465 = 807
思路
  1. 链表的加法器,每次将同位上的数字相加并记录进位位,注意遍历后要考虑l1/l2剩余以及仍有进位位的情况。
  2. 实现上利用dummy node, 编程会方便很多。利用一个dummy节点指向头节点,返回时返回dummy->next 即可。
// 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 && l2 == NULL) return NULL;
    if (l1 == NULL) return l2;
    if (l2 == NULL) return l1;
    int carry = 0;
    ListNode* dummy = new ListNode(0);
    ListNode* pNode = dummy;
    while (l1 && l2) {
      int newVal = l1->val + l2->val + carry;
      carry = newVal / 10;
      newVal = newVal % 10;
      ListNode* pTmp = new ListNode(newVal);
      pNode->next = pTmp;
      pNode = pNode->next;
      l1 = l1->next;
      l2 = l2->next;
    }
    while (l1) {
      int newVal = l1->val + carry;
      carry = newVal / 10;
      newVal = newVal % 10;
      ListNode* pTmp = new ListNode(newVal);
      pNode->next = pTmp;
      pNode = pNode->next;
      l1 = l1->next;  
    }
    while (l2) {
      int newVal = l2->val + carry;
      carry = newVal / 10;
      newVal = newVal % 10;
      ListNode* pTmp = new ListNode(newVal);
      pNode->next = pTmp;
      pNode = pNode->next;
      l2 = l2->next;  
    }
    if(carry) {
      ListNode* pTmp = new ListNode(carry);
      pNode->next = pTmp;
      pNode = pNode->next;
    }
    return dummy->next;
  }
};

你可能感兴趣的:(LeetCodeDay41 —— 两数相加★☆)