2 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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 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) {
ListNode* head = NULL;
ListNode* tail = NULL;
ListNode* p = l1;
ListNode* q = l2;
int carry = 0;
while(p != NULL || q != NULL)
{
int x = (p != NULL) ? p->val: 0;
int y = (q != NULL) ? q->val: 0;
int sum = x + y + carry;
carry = sum/10;
if(head == NULL)
{
head = new ListNode(sum%10);
tail = head;
}
else {
tail->next = new ListNode(sum%10);
tail = tail->next;
}
if(p != NULL) p = p->next;
if(q != NULL) q = q->next;
}
if(carry > 0)
{
tail->next = new ListNode(carry);
tail = tail->next;
}
return head;
}
};
第一次提交代码后发现运算速度并不快(54.2%),内存也不是最优,于是进行第二次迭代。
第二次迭代优化的内容有:
- 省掉了部分参数
- 合并了部分条件判断
- 简化了条件判断语句
最后的运行速度达到20ms(92.87%), 内存少于(71.69%)
/**
* 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* head = NULL;
ListNode* tail = NULL;
int carry = 0;
while(l1||l2)
{
int x,y,sum;
if(l1)
{
x = l1->val;
l1 = l1->next;
}
else x = 0;
if(l2)
{
y = l2->val;
l2 = l2->next;
}
else y = 0;
sum = x + y + carry;
carry = sum/10;
if(head == NULL)
{
head = new ListNode(sum%10);
tail = head;
}
else {
tail->next = new ListNode(sum%10);
tail = tail->next;
}
}
if(carry > 0)
{
tail->next = new ListNode(carry);
tail = tail->next;
}
return head;
}
};