问题描述
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
分析
1. 数字非负
2. 个十百千万顺序存储
3. 返回结果链表的头结点
代码:
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *result=NULL;
ListNode *i=l1;
ListNode *j=l2;
ListNode *tail = result;
while (i != NULL || j != NULL)
{
ListNode *temp = new (ListNode)(0);
if (i != NULL && j != NULL)
{
temp->val = i->val + j->val;
i = i->next;
j = j->next;
}
else if (i != NULL && j == NULL)
{
temp->val = i->val;
i = i->next;
}
else if (i == NULL && j != NULL)
{
temp->val = j->val;
j = j->next;
}
if (result == NULL)
{
result = temp;
}
else
{
tail->next = temp;
}
tail = temp;
}
tail = result;
while (tail)
{
if (tail->val >= 10)
{
if (tail->next == NULL)
{
tail->next = new (ListNode)(0);
}
tail->next->val += tail->val / 10;
tail->val %= 10;
}
tail = tail->next;
}
return result;
}
};
代码的复杂度分析:
空间复杂度 O(N)
- 返回了一个结果链表
时间复杂度 O(N)
- 循环了1遍加数和被加数的链表。
- 循环了1遍结果链表。