blob: 042e0e4b4a7fd01e075358cb973f0e2edc71be61 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
# 1171. Remove Zero Sum Consecutive Nodes from Linked List
"""
given the 'head' of a linked list, we repeatedly delete the consecutive
sequences of nodes that sum to 0 until there are no such sequences. after
doing so, return the head of the final linked list. you may return any such
answer.
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def removeZeroSumSublists(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
curr = tmp = ListNode(0)
tmp.next = head
prefix = 0
seen = collections.OrderedDict()
while curr:
prefix += curr.val
node = seen.get(prefix, curr)
while prefix in seen:
seen.popitem()
seen[prefix] = node
node.next = curr = curr.next
return tmp.next
|