leetcode 1
輸入數(shù)字個(gè)位在鏈表頭走贪,返回?cái)?shù)字個(gè)位在鏈表尾部
給你兩個(gè) 非空 的鏈表,表示兩個(gè)非負(fù)的整數(shù)惑芭。它們每位數(shù)字都是按照 逆序 的方式存儲的坠狡,并且每個(gè)節(jié)點(diǎn)只能存儲 一位 數(shù)字。
請你將兩個(gè)數(shù)相加遂跟,并以相同形式返回一個(gè)表示和的鏈表逃沿。
你可以假設(shè)除了數(shù)字 0 之外,這兩個(gè)數(shù)都不會以 0 開頭幻锁。
示例 1:
輸入:l1 = [2,4,3], l2 = [5,6,4]
輸出:[7,0,8]
解釋:342 + 465 = 807.
示例 2:
輸入:l1 = [0], l2 = [0]
輸出:[0]
示例 3:
輸入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
輸出:[8,9,9,9,0,0,0,1]
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
res = ListNode(-1)
p = res
carry = 0
while l1 or l2 or carry!= 0 :
if not l1:
num1 = 0
else:
num1 = l1.val
l1 = l1.next
if not l2:
num2 = 0
else:
num2 = l2.val
l2 = l2.next
sums = num1 + num2 + carry
carry = sums // 10
curr = sums % 10
node = ListNode(curr)
p.next = node
p = p.next
return res.next
leetcode 445
輸入數(shù)字個(gè)位在末尾凯亮,返回?cái)?shù)字個(gè)位在鏈表尾部
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
s1 ,s2 = [],[]
while l1:
s1.append(l1.val)
l1 = l1.next
while l2:
s2.append(l2.val)
l2 = l2.next
res,carry = None,0
while s1 or s2 or carry!= 0:
num1 = 0 if not s1 else s1.pop()
num2 = 0 if not s2 else s2.pop()
sums = num1 + num2 + carry
carry = sums // 10
curr = sums % 10
node = ListNode(curr)
node.next = res
res = node
return res
- 這里要將鏈表轉(zhuǎn)化為列表來做。
- 另一個(gè)技巧點(diǎn)是
s1.pop()
這個(gè)用法哄尔,既取到了后面的數(shù)字假消,又去掉了數(shù)字 - 還有將鏈表穿起來時(shí),每一次新生成的節(jié)點(diǎn)的next置為上次的結(jié)果
82: 刪除排序鏈表中的重復(fù)元素
存在一個(gè)按升序排列的鏈表岭接,給你這個(gè)鏈表的頭節(jié)點(diǎn) head 富拗,請你刪除鏈表中所有存在數(shù)字重復(fù)情況的節(jié)點(diǎn),只保留原始鏈表中 沒有重復(fù)出現(xiàn) 的數(shù)字鸣戴。
返回同樣按升序排列的結(jié)果鏈表媒峡。
這道題和他的相似題目(簡單)的區(qū)別在于,只要出現(xiàn)重復(fù)葵擎,那么就要?jiǎng)h除鏈表中所有的節(jié)點(diǎn),一個(gè)都不允許留半哟。比如:輸入:head = [1,2,3,3,4,4,5]酬滤,刪除后要輸出:[1,2,5]。簡單題目是要留下一個(gè)寓涨。
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
dummy = ListNode()
dummy.next = head
same = None
p = head
pre = dummy
while p :
nexxt = p.next
if nexxt and nexxt.val == p.val or nexxt and nexxt.val==same:
same = nexxt.val
pre.next = nexxt.next
p = pre
continue
pre = p
p = p.next
return dummy.next
這里我用了一個(gè)same變量來保存我刪除的節(jié)點(diǎn)是什么值盯串,這么做的目的在于,很可能刪除這倆一樣的元素之后戒良,后面緊跟著又是一個(gè)相等值的元素体捏,那這個(gè)時(shí)候其實(shí)這個(gè)第三個(gè)元素也是需要?jiǎng)h除的。
之前same=nexxt.val這個(gè)地方我寫的是same = p.val。一開始想的是既然兩個(gè)值都一樣几缭,只要保存他們的相同值就可以了河泳,但是如果是if條件的第二個(gè)情況滿足,這個(gè)same值就不會變化了年栓。這樣就會出現(xiàn)一個(gè)問題拆挥,那就是如果是[1,1,1,1]這種情況,最后一個(gè)1還是會輸出某抓,那這樣結(jié)果就不對了纸兔。愿意在于,這里的p是可能為dummy空節(jié)點(diǎn)的否副。