問題
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.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
分析:關鍵是解決進位問題,val = l1.val + l2.val + 進位。 需要判斷l1和l2是否是結尾,對結尾情況作出處理。最後一位進位需要在末尾加一個鏈。
PS:java需要引用實體對象才能算是真正的引用
java
開始的做法:
/**
* 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) {
int temp = 0;
ListNode res = new ListNode(0);
ListNode now = res, p = l1, q = l2;
while(p != null && q != null){
int val = p.val + q.val + temp;
now.next = new ListNode(val%10);
temp = val / 10;
now = now.next;
p = p.next;
q = q.next;
}
ListNode lastL = null;
if(p != null){
lastL = p;
}
else if(q != null){
lastL = q;
}
while(lastL != null){
int val = lastL.val + temp;
now.next = new ListNode(val%10);
temp = val / 10;
now = now.next;
lastL = lastL.next;
}
if(temp != 0){
now.next = new ListNode(temp);
}
return res.next;
}
}
簡化代碼,可以在兩個鏈表相加時,空鏈表當前值設置爲0:
/**
* 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) {
int temp = 0, val, pval, qval;
ListNode res = new ListNode(0);
ListNode now = res, p = l1, q = l2;
while(p != null || q != null){
pval = p != null ? p.val : 0;
qval = q != null ? q.val : 0;
val = pval + qval + temp;
now.next = new ListNode(val % 10);
temp = val / 10;
now = now.next;
if(p != null) p = p.next;
if(q != null) q = q.next;
}
if(temp != 0){
now.next = new ListNode(temp);
}
return res.next;
}
}
Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
res = ListNode(0)
now = res
p = l1
q = l2
carry = 0 #進位
while p or q:
pval = p.val if p else 0
qval = q.val if q else 0
val = carry + pval + qval
now.next = ListNode(val % 10)
carry = val // 10
now = now.next
if p: p = p.next
if q: q = q.next
if carry:
now.next = ListNode(carry)
return res.next