您需要跟踪每个节点的值和起始Node
对象本身,因为这是一个循环链表。您的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]