You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
题意:链表相加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) {
ListNode *l3 = reverseList(l1);
ListNode *l4 = reverseList(l2);
if(l3 == NULL) return l4;
if(l4 == NULL) return l3;
ListNode dummy(0);
ListNode *cur = &dummy;
int carry = 0;
while(l3 || l4){
if(l3){
carry += l3->val;
l3 = l3->next;
}
if(l4){
carry += l4->val;
l4 = l4->next;
}
cur->next = new ListNode(carry % 10);
carry /= 10;
cur = cur->next;
}
if(carry) cur->next = new ListNode(1);
return reverseList(dummy.next);
}
ListNode *reverseList(ListNode *head){
ListNode dummy(0);
dummy.next = head;
ListNode *pre = head, *cur = pre->next;
while(cur){
pre->next = cur->next;
cur->next = dummy.next;
dummy.next = cur;
cur = pre->next;
}
return dummy.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) {
stack<int> s1, s2;
while(l1){
s1.push(l1->val);
l1 = l1->next;
}
while(l2){
s2.push(l2->val);
l2 = l2->next;
}
int carry = 0;
ListNode *pre = NULL, *cur = NULL;
while(s1.size() || s2.size() || carry){
int sum = carry;
if(s1.size()){
sum += s1.top();
s1.pop();
}
if(s2.size()){
sum += s2.top();
s2.pop();
}
carry = sum / 10;
pre = new ListNode(sum % 10);
pre->next = cur;
cur = pre;
}
return cur;
}
};