- 做者:陳大魚頭
- 項目地址:ying-leetcode
- 碎碎念:Mmmmm,不按期刷leetcode,會以JS TS PY的形式輸出出來
給出兩個 非空 的鏈表用來表示兩個非負的整數。其中,它們各自的位數是按照 逆序 的方式存儲的,而且它們的每一個節點只能存儲 一位 數字。javascript
若是,咱們將這兩個數相加起來,則會返回一個新的鏈表來表示它們的和。java
您能夠假設除了數字 0 以外,這兩個數都不會以 0 開頭。node
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 輸出:7 -> 0 -> 8 緣由:342 + 465 = 807python
其實這題比較簡單,無非是兩個鏈表之間同層級的數字相加,惟一要注意的就是若是相加以後數字大於10,須要往下一級+1,當前級數是個位的那個數字。基本也是一個循環能夠解決的。再注意處理下,若是一個鏈表長度長於另外一個鏈表時的邊界處理,其他就沒啥了。git
/** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */
const addTwoNumbers = (l1, l2) => {
let l3 = null
let cache = 0
let tens = 0
while (l1 || l2) {
let total = 0
if (l1) {
let l1Head = l1.val
total += l1Head
l1 = l1.next
}
if (l2) {
let l2Head = l2.val
total += l2Head
l2 = l2.next
}
total += tens
if (total >= 10) {
total -= 10
tens = 1
} else {
tens = 0
}
let node = new ListNode(total)
if (cache) {
cache.next = node
cache = node
} else {
l3 = node
cache = l3
}
}
if (tens === 1) {
cache.next = new ListNode(1)
}
return l3
}
複製代碼
class ListNode {
val: number
next: ListNode | any
constructor(value: number) {
this.val = value
this.next = null
}
}
/** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */
const addTwoNumbers = (l1: ListNode, l2: ListNode) => {
let l3: null | ListNode = null
let cache: ListNode | null = null
let tens: number = 0
while (l1 || l2) {
let total: number = 0
if (l1) {
let l1Head = l1.val
total += l1Head
l1 = l1.next
}
if (l2) {
let l2Head = l2.val
total += l2Head
l2 = l2.next
}
total += tens
if (total >= 10) {
total -= 10
tens = 1
} else {
tens = 0
}
let node = new ListNode(total)
if (cache) {
cache.next = node
cache = node
} else {
l3 = node
cache = l3
}
}
if (tens === 1) {
cache.next = new ListNode(1)
}
return l3
}
複製代碼
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
""" :type l1: ListNode :type l2: ListNode :rtype: ListNode """
l3 = None
cache = 0
tens = 0
while l1 or l2:
total = 0
if l1:
l1Head = l1.val
total = total + l1Head
l1 = l1.next
if l2:
l1Head = l2.val
total = total + l1Head
l2 = l2.next
total = total + tens
if total >= 10:
total = total - 10
tens = 1
else:
tens = 0
node = ListNode(total)
if cache:
cache.next = node
cache = node
else:
l3 = node
cache = l3
if tens == 1:
cache.next = ListNode(1)
return l3
複製代碼
若是你、喜歡探討技術,或者對本文有任何的意見或建議,你能夠掃描下方二維碼,關注微信公衆號「 魚頭的Web海洋 」,隨時與魚頭互動。歡迎!衷心但願能夠碰見你。github