首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何删除链表中相加为0的连续元素

如何删除链表中相加为0的连续元素
EN

Stack Overflow用户
提问于 2019-08-23 14:04:14
回答 1查看 220关注 0票数 3

我正在编写一段Python代码来删除链表中那些相加为0的连续元素

链表定义如下:

代码语言:javascript
复制
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 -> 14 -> -4需要去掉,因为它们加起来就是0

遍历元素之后,如下所示

代码语言:javascript
复制
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的连续元素的子集。因为它是herehere所讨论的NP-Complete problem。我如何设计算法来找到解决方案?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-23 14:24:32

您可以尝试递归或嵌套循环,因为您应该在计算总和时尝试从每个节点开始。一个简单的实现可能如下所示:

代码语言:javascript
复制
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.next
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57620642

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档