1、题目描述
难度中等26
给定两个用链表表示的整数,每个节点包含一个数位。
这些数位是反向存放的,也就是个位排在链表首部。
编写函数对这两个整数求和,并用链表形式返回结果。
示例:
输入:(7 -> 1 -> 6) + (5 -> 9 -> 2),即617 + 295 输出:2 -> 1 -> 9,即912进阶:假设这些数位是正向存放的,请再做一遍。
示例:
输入:(6 -> 1 -> 7) + (2 -> 9 -> 5),即617 + 295 输出:9 -> 1 -> 2,即912
2、上代码
使用一个虚拟头结点dummy
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(-1);
ListNode p = dummy;
int sum = 0, carry = 0; //carry代表进位
while(l1 != null || l2 != null || carry > 0) {
sum = 0; //每次循环sum都置为0
if(l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if(l2 != null) {
sum += l2.val;
l2 = l2.next;
}
sum += carry;
ListNode newNode = new ListNode(-1);
newNode.val = (sum >= 10)? sum % 10 : sum;
newNode.next = null;
carry = (sum >= 10)? sum / 10 : 0;
p.next = newNode;
p = p.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) {
if (!l1 || !l2) {
return l1 == nullptr ? l2 : l1;
}
int carry = 0;
ListNode* ret = new ListNode(0);
ListNode* p = ret;
while (l1 && l2) {
int sum = l1->val + l2->val + carry;
p->next = new ListNode(sum % 10);
carry = sum / 10;
l1 = l1->next;
l2 = l2->next;
p = p->next;
}
while (l1) {
int sum = l1->val + carry;
p->next = new ListNode(sum % 10);
carry = sum / 10;
l1 = l1->next;
p = p->next;
}
while (l2) {
int sum = l2->val + carry;
p->next = new ListNode(sum % 10);
carry = sum / 10;
l2 = l2->next;
p = p->next;
}
if (carry) {
p->next = new ListNode(carry);
}
return ret->next;
}
};