2017六省聯考部分題目整理【期末考試,壽司餐廳,組合數問題,分手是祝願】
阿新 • • 發佈:2020-11-28
此文轉載自:https://blog.csdn.net/qq_36556893/article/details/110231369#commentBox
目錄
一、題目內容
給你兩個 非空 連結串列來代表兩個非負整數。數字最高位位於連結串列開始位置。它們的每個節點只儲存一位數字。將這兩數相加會返回一個新的連結串列。
你可以假設除了數字 0 之外,這兩個數字都不會以零開頭。
進階:
如果輸入連結串列不能修改該如何處理?換句話說,你不能對列表中的節點進行翻轉。
示例:
輸入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 8 -> 0 -> 7
二、解題思路
哎,太難了,還是兩個函式來回套吧:
1.兩數相加:leetcode_2. 兩數相加
2.反轉連結串列:leetcode_206. 反轉連結串列
三、程式碼
# 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: head = self._addTwoNumbers(self.reverseList(l1), self.reverseList(l2)) return self.reverseList(head) def _addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ head = ListNode(0) # print(head.val, head.next) p = head q = p carry = 0 while l1 or l2: if l1 is not None: l1_val = l1.val # print("l1:", l1_val) else: l1_val = 0 if l2 is not None: l2_val = l2.val # print("l2:", l2_val) else: l2_val = 0 temp = l1_val + l2_val + carry if temp >= 10: carry = 1 p.val = temp - 10 p.next = ListNode(1) else: carry = 0 p.val = temp p.next = ListNode(0) q = p p = p.next if l1 is not None: l1 = l1.next if l2 is not None: l2 = l2.next if q.next.val == 0: q.next = None del p return head def reverseList(self, head: ListNode): # null 1 --> 2 --> 3 --> 4 --> null # null <-- 1 <-- 2 <-- 3 <-- 4 null if not head: return None cur, cur_new_next = head, None while cur: # save original next node origin_next = cur.next # link new next node cur.next = cur_new_next # current node turns to new next node cur_new_next = cur # original next node turns to current node cur = origin_next return cur_new_next