题目描述
解题思路
Java
代码
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode res = null; //结果链表,不可移动,一旦移动就会丢失值
ListNode cur = null; //结果链表的游标,可移动,为了往结果链表中添加
int upval = 0; //进位值
//情况一
while(l1 != null && l2 != null){
int val1 = l1.val;
int val2 = l2.val;
int val = val1 + val2 + upval;
upval = val / 10;
int curval = val % 10;
ListNode thisNode = new ListNode(curval);
if(res == null){
res = thisNode;
cur = res;
}else{
cur.next = thisNode;
cur = thisNode;
}
l1 = l1.next;
l2 = l2.next;
}
//情况二
while(l1 == null && l2 != null){ //l1长度小于l2
int val = l2.val + upval;
upval = val / 10;
int curval = val % 10;
ListNode thisNode = new ListNode(curval);
if(res == null){
res = thisNode;
cur = res;
}else{
cur.next = thisNode;
cur = thisNode;
}
l2 = l2.next;
}
//情况三
while(l2 == null && l1 != null){ //l2长度小于l1
int val = l1.val + upval;
upval = val / 10;
int curval = val % 10;
ListNode thisNode = new ListNode(curval);
if(res == null){
res = thisNode;
cur = res;
}else{
cur.next = thisNode;
cur = thisNode;
}
l1 = l1.next;
}
if(upval != 0){
ListNode thisNode = new ListNode(upval);
cur.next = thisNode;
}
return res;
}
}
此代码还可以整合下,我这么写主要是为了看起来和图示搭配,可以按下面两个代码的方式写,看起来简单点
Python3
代码
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 is None:
return l2
if l2 is None:
return l1
res = ListNode(0)
cur = res
upval = 0
while l1 or l2:
tmpsum = 0
if l1: # 情况二
tmpsum = l1.val
l1 = l1.next
if l2: # 情况三
tmpsum += l2.val
l2 = l2.next
curval = (tmpsum + upval) % 10
upval = (tmpsum + upval) // 10
cur.next = ListNode(curval)
cur = cur.next
# 最后一位是否进位
if upval:
cur.next = ListNode(1)
del cur
res = res.next
return res
C++
代码
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if(l1 == NULL){
return l2;
}
if(l2 == NULL){
return l1;
}
ListNode* res = new ListNode(0);
ListNode* cur = res;
int upval = 0;
while(l1 != NULL || l2 != NULL){
int tmpsum = 0;
if(l1 != NULL){
tmpsum = l1->val;
l1 = l1->next;
}
if(l2 != NULL){
tmpsum += l2->val;
l2 = l2->next;
}
int curval = (tmpsum + upval) % 10;
upval = (tmpsum + upval) / 10;
cur->next = new ListNode(curval);
cur = cur->next;
}
if(upval != 0){
cur->next = new ListNode(1);
}
res = res->next;
return res;
}
};