Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 删除循环链表中的重复项_Python_Algorithm_Python 2.7_Python 3.x - Fatal编程技术网

Python 删除循环链表中的重复项

Python 删除循环链表中的重复项,python,algorithm,python-2.7,python-3.x,Python,Algorithm,Python 2.7,Python 3.x,必须删除相同值的重复出现。如果从head遍历的(链接)列表在调用后包含序列3,2,8,8,8,5,2,3 last = Node(3) head = Node(2, last) head = Node(5, head) head = Node(8, head) head = Node(8, head) head = Node(8, head) head = Node(2, head) head = Node(3, head) last.next = head 现在,从head遍历的列表应该包含

必须删除相同值的重复出现。如果从head遍历的(链接)列表在调用后包含序列3,2,8,8,8,5,2,3

last = Node(3)
head = Node(2, last)
head = Node(5, head)
head = Node(8, head)
head = Node(8, head)
head = Node(8, head)
head = Node(2, head)
head = Node(3, head)
last.next = head
现在,从head遍历的列表应该包含3、2、8、5、2或2、8、5、2、3。
“head”的值等于None表示一个空列表(包含零个元素的列表)。我将如何实现这一点。这可能是最容易实现的方法之一。由于我是Python新手,我很难做到这一点。

迭代循环列表,丢弃已经出现的值(但首先检查该节点是否已经被查看)


基本上,从头部开始,每次检查节点的值是否在集合中。如果不是,则将该值添加到集合并继续。否则,当您回到第一个节点时(您永远不会删除第一个节点),请删除该节点(将上一个节点和下一个节点连接在一起),停止。

您需要跟踪每个节点的值和开始的
节点
对象本身,因为这是一个循环链接列表。
节点
类的代码可能不同,但修改函数应该很容易

class Node(object):
    def __init__(self, data, next_=None):
        self.data = data
        self.next = next_

def ll_remove_dups(curr):
    start_node = curr
    values_seen = {curr.data}
    while curr.next is not start_node:
        if curr.next.data in values_seen:
            curr.next = curr.next.next
        else:
            values_seen.add(curr.next.data)
            curr = curr.next

def ll_traverse(curr):
    start_node = curr
    yield curr.data
    while curr.next is not start_node:
        yield curr.next.data
        curr = curr.next

if __name__ == "__main__":
    last = Node(3)
    head = Node(3, Node(2, Node(8, Node(8, Node(8, Node(5, Node(2, last)))))))
    last.next = head

    print list(ll_traverse(head))  # [3, 2, 8, 8, 8, 5, 2, 3]
    ll_remove_dups(head)
    print list(ll_traverse(head))  # [3, 2, 8, 5]

我将如何在python中定义列表的头值。(头)给了我一个错误。另外,错误list.object没有属性数据的原因可能是什么(对于行:values_seen={curr.data}我复制了u发布的一个。我得到了两个错误1.没有为list定义head(ll_traverse(head)),2.list没有值_seen={curr.data}的属性数据.请帮我做这个。谢谢-reetu@user2720244我认为我暗指使用解释器来评估函数调用,这让您感到困惑。请参阅完整脚本的新答案。