LeetCode 算法习题 第二周

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

题目大意

给定一个数据结构,一个ListNode包含它的value值和一个指向另一个ListNode的next指针,用它们倒序保存一个整数。我们要将输入的两个ListNode加起来。给的示例即为 342 + 465 = 807。

我的解答

/**
 * 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) {
        int a = 0; //a为进位
        ListNode result(0); //用于保存结果
        ListNode* temp = &result; //声明一个指向result的指针

      while((l1 != NULL) ||(l2 != NULL)|| a ){
         int  sum = 0;
         sum = (l1 != NULL ? l1->val : 0) + (l2 != NULL ? l2->val : 0) + a;
         a = sum / 10; //若两数加起来大于等于十,则有进位

         temp->next = new ListNode(sum % 10);
 // 将计算结果作为下一个节点的值
         temp = temp->next;
 // 指针指向下一节点
         l1 = l1 ? l1->next : l1;
         l2 = l2 ? l2->next : l2;
 //两输入若有一个为NULL,则该指针不向后移动,即一直指向NULL,则两数相加时,该加数为0
      }

    return result.next;
 //因为之前保存结果是从result.next开始保存的,所以我们返回result.next.
    }
};

你可能感兴趣的:(LeetCode 算法习题 第二周)