我正在编写一段Python代码来删除链表中那些相加为0的连续元素
链表定义如下:
class Node:
def __init__(self, val, next=None):
self.value = val
self.next = next
node = Node(10)
node.next = Node(5)
node.next.next = Node(-3)
node.next.next.next = Node(-3)
node.next.next.next.next = Node(1)
node.next.next.next.next.next = Node(4)
node.next.next.next.next.next.next = Node(-4)从上面的数据来看,5 -> -3 -> -3 -> 1和4 -> -4需要去掉,因为它们加起来就是0。
遍历元素之后,如下所示
def removeConsecutiveSumTo0(node):
start = node
while start:
mod = False
total = 0
end = start
while end:
total += end.value
if total == 0:
start = end
mod = True
break
end = end.next
if mod == False:
res = start
start = start.next
return res
node = removeConsecutiveSumTo0(node)
while node:
print (node.value, end=' ')
node = node.next
# 10 (Expected output)我无法创建包含相加为0的连续元素的子集。因为它是here和here所讨论的NP-Complete problem。我如何设计算法来找到解决方案?
发布于 2019-08-23 14:24:32
您可以尝试递归或嵌套循环,因为您应该在计算总和时尝试从每个节点开始。一个简单的实现可能如下所示:
def removeConsecutiveSumTo0(node):
start = node
while start.next:
total = 0
cur = start.next
while cur:
total += cur.value
if total == 0:
start.next = cur.next
break
cur = cur.next
else:
start = start.nexthttps://stackoverflow.com/questions/57620642
复制相似问题