# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution(object): defremoveZeroSumSublists(self, head): """ :type head: ListNode :rtype: ListNode """ dummy = ListNode() dummy.next = head pre = 0 dic = {} dic[0] = dummy
# 記錄 Pre Sum 狀態,提供捷徑的概念 while head != None: pre += head.val dic[pre] = head head = head.next head = dummy pre = 0 # 有捷徑就跳,且是往最後一次相同 Pre Sum 的出口跳 while head != None: pre += head.val head.next = dic[pre].next head = head.next return dummy.next
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution(object): defremoveZeroSumSublists(self, head): """ :type head: ListNode :rtype: ListNode """ arr = [] dummy = head
# 取出數組 while dummy != None: if dummy.val != 0: arr.append(dummy.val) dummy = dummy.next
n = len(arr)
# 透過 Stack 方式將合為 0 之組合拿掉 stk = [] for c in arr: iflen(stk) != 0: tot = c for i inrange(len(stk)-1, -1, -1): tot += stk[i] if tot == 0: stk = stk[:i] break else: stk.append(c)
else: stk.append(c)
# 重建 Linked List dummy = ListNode(0) res = dummy for c in stk: dummy.next = ListNode(c) dummy = dummy.next return res.next