leetcode2两数相加:给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
思路:记录和sum和进位标志r
/**
* 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* result = new ListNode(0);
ListNode* tmp = result;
int sum = 0, r = 0;
while(l1 || l2)
{
int a = (l1 != NULL)?l1->val:0;
int b = (l2 != NULL)?l2->val:0;
sum = a + b + r;
r = sum / 10;
tmp->next = new ListNode(sum % 10);
tmp = tmp->next;
if(l1 != NULL) l1 = l1->next;
if(l2 != NULL) l2 = l2->next;
}
if(r == 1) tmp->next = new ListNode(1);
return result->next;
}
};
leetcode445 两数相加 II:给定两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
进阶:
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
思路:考虑到进阶要求,不能反转链表,那么只能借助栈(或数组)。由于返回的链表是从高位起的,那么在形成链表的时候适合用头插法,而不必最后再反转链表。
示例:
输入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 8 -> 0 -> 7
/**
* 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;
}
ListNode* dummy = new ListNode(INT_MAX);
int carry = 0, curSum = 0;
while(s1.size() || s2.size())
{
curSum = carry;
if(s1.size())
{
curSum += s1.top();
s1.pop();
}
if(s2.size())
{
curSum += s2.top();
s2.pop();
}
carry = curSum > 9? 1: 0;
curSum %= 10;
//相当于将temp插在dummy的头部后面
ListNode* temp = new ListNode(curSum);
temp->next = dummy->next;
dummy->next = temp;
}
if(carry)
{
ListNode* temp = new ListNode(1);
temp->next = dummy->next;
dummy->next = temp;
}
return dummy->next;
}
};