Description:
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.
描述:
给定两个非空链表,分别表示两个非负整数。整数的组成数字按照逆序排列,并且链表的每个节点表示一个数字。将两个整数相加,并以链表的形式返回相加和。
假设两个整数均不包含前导0(除了整数0本身)。
例子:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 解释: 342 + 465 = 807
遍历两个数字,并逐节点相加。以变量carrier表示进位。
/** * 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 *p1 = l1; ListNode *p2 = l2; int carrier = 0; ListNode *l3 = NULL; ListNode *p = NULL; while(p1 != NULL || p2 != NULL) { int val1 = p1 == NULL ? 0 : p1->val; int val2 = p2 == NULL ? 0 : p2->val; p1 = p1 == NULL ? NULL : p1->next; p2 = p2 == NULL ? NULL : p2->next; int val = val1 + val2 + carrier; carrier = val >= 10 ? 1 : 0; val = val >= 10 ? val - 10 : val; ListNode *node = new ListNode(val); if(l3 == NULL) { l3 = p = node; } else { p->next = node; p = node; } } if(carrier) { ListNode *node = new ListNode(carrier); p->next = node; } return l3; } };
时间复杂度为O(max(n1, n2)), 空间复杂度为O(max(n1, n2) + 1)。