LeetCode 2.Add Two Numbers
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
分析:
据题目的要求知,两个多位数按逆序用链表将每一位的数字(取值范围为0~9)存储起来,然后每位数字对应相加(要进行进位处理),相加的结果也用链表存储起来。
最简单、易理解的解法:
像题目所说的那样,将每位数字对应相加,较长的链表后面的数字直接接在结果链表后面即可,然后统一处理进位。
/**
* 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, *p2, *p3;
ListNode *head, *tail;
p1 = l1;
p2 = l2;
head = tail = NULL;
while (p1 != NULL && p2 != NULL) {
p3 = new ListNode(p1 -> val + p2 -> val);
if (tail == NULL) {
head = tail = p3;
} else {
tail -> next = p3;
tail = p3;
}
p1 = p1 -> next;
p2 = p2 -> next;
}
while (p1 != NULL) {
p3 = new ListNode(p1 -> val);
tail -> next = p3;
tail = p3;
p1 = p1 -> next;
}
while (p2 != NULL) {
p3 = new ListNode(p2 -> val);
tail -> next = p3;
tail = p3;
p2 = p2 -> next;
}
p3 = head;
while (p3 -> next != NULL) {
p3 -> next -> val += p3 -> val / 10;
p3 -> val %= 10;
p3 = p3 -> next;
}
while (p3 -> next == NULL && p3 -> val >= 10) {
p3 -> next = new ListNode(p3 -> val / 10);
p3 -> val %= 10;
p3 = p3 -> next;
}
return head;
}
};
复杂度分析:
假设l1的长度为m,l2的长度为n。
时间复杂度:O(max(m, n))。在进行数字位相加时,至多进行了max(m, n)次;在处理进位时,至多了进行了max(m , n) 次。O(2 * max(m, n)) 约等于O(max(m, n))
空间复杂度:O(max(m, n))。因为结果链表的长度至多会是max(m, n) + 1
更简洁的解法:
在下面这个解法中,可以理解为:两个多位数长度不一致时,给长度较小的多位数的高位补0,这样得到的两个多位数可看成长度相等,逐位相加即可;
另外,在进行相加时,顺便处理进位:用carry记录进位,用sum对10取模获得0~9之间的数字。
时间复杂度和空间复杂度均是O(max(m, n))。
/**
* 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, *p2, *p3;
ListNode *head, *tail;
p1 = l1;
p2 = l2;
head = tail = NULL;
int carry = 0;
while (p1 != NULL || p2 != NULL) {
int x = (p1 != NULL) ? p1 -> val : 0;
int y = (p2 != NULL) ? p2 -> val : 0;
int sum = x + y + carry;
carry = sum / 10;
sum %= 10;
p3 = new ListNode(sum);
if (tail == NULL) {
head = tail = p3;
} else {
tail -> next = p3;
tail = p3;
}
if (p1 != NULL) p1 = p1 -> next;
if (p2 != NULL) p2 = p2 -> next;
}
if (carry > 0) {
tail -> next = new ListNode(carry);
}
return head;
}
};