简体   繁体   English

删除重复的Python循环链接列表

[英]Remove Duplicates Python Circular Linked List

Duplicate occurance of the same value has to be removed. 必须删除相同值的重复出现。 If the (linked)list traversed from head contains sequence 3,2,8,8,8,5,2,3 after calling 如果从头开始遍历的(链接)列表在调用后包含序列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

Now, the list, traversed from head, should contain 3, 2, 8, 5, 2 or 2, 8, 5, 2, 3. The value of 'head' equal None represents an empty list (a list having zero elements). 现在,从head遍历的列表应包含3、2、8、5、2或2、8、5、2、3。'head'的值等于None表示一个空列表(一个具有零个元素的列表) 。 How would I achieve this. 我将如何实现这一目标。 This may be one of the easiest way to achieve. 这可能是最简单的方法之一。 Since I am new to Python am having hard time in doing this. 由于我刚接触Python,因此很难做到这一点。

You need to keep track of the values for each node and the starting Node object itself, since this is a circular linked list. 您需要跟踪每个节点的值以及起始Node对象本身,因为这是一个循环链接列表。 Your code for the Node class may be different but it should be easy to modify the functions. 您的Node类代码可能有所不同,但修改函数应该很容易。

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]

Iterate over the circular list, discarding values which have already appeared (but checking first to see if that node has already been looked at). 遍历循环列表,丢弃已经出现的值(但首先检查是否已查看该节点)。

Basically, start from the head, and each time checking to see if the value of the node is in a set. 基本上,从头开始,每次检查节点的值是否在集合中。 If it isn't add the value to the set and move on. 如果不是,则将值添加到集合中并继续。 Otherwise, remove the node (join the previous and the next nodes together) When you happen back upon the first node (you'll never delete the first node), stop. 否则,请删除该节点(将上一个节点和下一个节点连接在一起)。当您回到第一个节点时(永远不会删除第一个节点),请停止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM