###### tags: `LeetCode`,`Python3`,`Medium` # 1171. Remove Zero Sum Consecutive Nodes from Linked List ### **題目連結:** [**Remove Zero Sum Consecutive Nodes from Linked List**]([填入連結](https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/?envType=daily-question&envId=2024-03-12)) ### **解題方向** * 此題要用prefix_sum的方式來解題 * 第一次遍歷:prefix和與節點的映射(HashTable),結束後我們會獲得一個{PrefixSum:List}的HashTable * 重置變數 * 第二次遍歷:移除總和為0的連續節點 * 直接連接到prefix和(前綴和)最後出現的節點,以此來移除中間總和為0的連續節點 * head.next=hashTable[prefix_sum].next -> 要跳過,所以才要.next,因為第一個值有被累加進prefix_sum ### **完整程式碼** ```Python= # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]: dummy=ListNode(0) dummy.next=head prefix_sum=0 hashTable={0:dummy} print('init') print('List : ',hashTable[prefix_sum],', PrefixSum : ',prefix_sum) print() # 第一次遍歷:prefix和與節點的映射 while head: prefix_sum+=head.val #prefix加了此List的起始值 hashTable[prefix_sum]=head print('(key)PrefixSum : ',prefix_sum,' (Value)List : ',hashTable[prefix_sum]) print() head=head.next # 重置prefix和head prefix_sum=0 head=dummy print('完整Table:',hashTable) # 第二次遍歷:移除總和為0的連續節點 while head: prefix_sum+=head.val print('sum=',prefix_sum,' head.val=',head.val) # 直接連接到prefix和(前綴和)最後出現的節點,以此來移除中間總和為0的連續節點 head.next=hashTable[prefix_sum].next # 要跳過,所以才要.next head=head.next return dummy.next ```