精華區beta Marginalman 關於我們 聯絡資訊
https://leetcode.com/problems/merge-nodes-in-between-zeros 2181. Merge Nodes in Between Zeros 給定一linked list head 請合併0-0之間的節點 此節點的值為合併節點之總和 修改後的linked list不可包含0 Example 1: Input: head = [0,3,1,0,4,5,2,0] Output: [4,11] Explanation: The above figure represents the given linked list. The modified list contains - The sum of the nodes marked in green: 3 + 1 = 4. - The sum of the nodes marked in red: 4 + 5 + 2 = 11. Example 2: Input: head = [0,1,0,3,0,2,2,0] Output: [1,3,4] Explanation: The above figure represents the given linked list. The modified list contains - The sum of the nodes marked in green: 1 = 1. - The sum of the nodes marked in red: 3 = 3. - The sum of the nodes marked in yellow: 2 + 2 = 4. Constraints: The number of nodes in the list is in the range [3, 2 * 105]. 0 <= Node.val <= 1000 There are no two consecutive nodes with Node.val == 0. The beginning and end of the linked list have Node.val == 0. 思路: 蝦雞巴寫 我幾百年沒碰linked list 對啊 大概就遇到0 創新node 沒有就加總 Python Code: class Solution: def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]: total = 0 result = ListNode() tmp = result head = head.next while head: if head.val == 0: tmp.next = ListNode(total) tmp = tmp.next total = 0 else: total += head.val head = head.next return result.next -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.194.160.111 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1720056712.A.5AC.html
Furina: 大師 07/04 09:32
DJYOMIYAHINA: 大師 07/04 10:25
smart0eddie: 大師 07/04 13:55