暴力大法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeZeroSumSublists(self, head: ListNode) -> ListNode:
lst = []
p = head
while p:
lst.append(p.val)
p = p.next
while True:
i,j = 0,1
flag = False
while i<len(lst):
if j<=len(lst):
if sum(lst[i:j]) == 0:
flag = True
del lst[i:j]
else:
j += 1
else:
i += 1
j = i+1
if flag == False:
break
nh = ListNode(-1)
p = nh
for i in range(len(lst)):
p.next = ListNode(lst[i])
p = p.next
return nh.next
前缀和
方法比较巧妙
首先拼接一个假结点,然后建立 前缀和<->结点 的映射,然后对于重复的前缀和,覆盖最后一个节点
对于 1,2,3,-3,-2的数组可以得到前缀和
[0,1,3,6,3,1]
如果两个结点的前缀和相同,那么它们中间的结点和为0,可以直接删除
删除操作用next来更新即可
class Solution:
def removeZeroSumSublists(self, head: ListNode) -> ListNode:
dct = dict()
dh = ListNode(0)
dh.next = head
p = dh
sumv = 0
while p:
sumv += p.val
dct[sumv] = p
p = p.next
p = dh
sumv = 0
while p:
sumv += p.val
p.next = dct.get(sumv).next
p = p.next
return dh.next