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)
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
题目大意:给出两个非空链表,要求遍历这两个链表,同时按位相加,同时将相加结果用链表相连,(注意:相加结果只能出现个位,其他位需进到下一组数的相加)。
可能出现的测试用例:
1、l1或l2为空;
2、l1,l2不为空,最后两个数相加也没有进位;
3、l1,l2不为空,最后两个数相加有进位;
解题思路:这道题不算难。
建立一个头结点,定义一个结构体指针指向该头结点,定义一个sum,ten分别表示两数 相加之和,进位;
当l1或l2不为空,或者其他位存在时(为了考虑情况3),进入循环;
然后将用来带头结点的链表将相加之和链接起来;
将头结点的next返回;
/**
* 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 = new ListNode(0);
ListNode* p = head;
int ten = 0;
int sum = 0;
while(l1 || l2 || ten)
{
sum = (l1?l1->val:0)+(l2?l2->val:0)+ten;
ten = sum/10;
p->next = new ListNode(sum%10);
p = p->next;
if(l1 != NULL){
l1 = l1->next;
}
if(l2 != NULL){
l2 = l2->next;
}
}
return head->next;
}
};