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)
Output: 7 -> 0 -> 8
用非空链表存储两个整数的各个位,然后求这两个数的和。
直接重新申请了一个链表用来存储结果。
时间复杂度:O(n)
空间复杂度:O(n)
也可以在原链表上存储结果。但是需要判断l1、l2是否为空,代码比较繁琐。但空间复杂度可将为O(1).
/**
* 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) {
//想加的结果存放在l1里,如果最后有进位,则new一个结点,然后插入到l1尾部
int c = 0;//进位
int sum = 0;//两个对应结点的和
ListNode dummy_head(-1);
ListNode *p = &dummy_head;
//ListNode *dummy_head = new ListNode(-1);
while(l1 != NULL || l2 != NULL){
// int sum = cpl1 -> val + cpl2 -> val + c; 如果两个节点都不为空,sum的求法直接可用此式,但是需要考虑l1或者l2是否为空,所以分解求sum
if(l1 != NULL){
sum += l1 -> val;
l1 = l1 -> next;
}
if(l2 != NULL){
sum += l2 -> val;
l2 = l2 -> next;
}
sum += c;
p -> next = new ListNode(sum % 10);
p = p -> next;
c = sum / 10;
sum = 0;
}
//判断最后的进位是否为0
if( c == 1){
p -> next = new ListNode(1);
}
return dummy_head.next;
}
};