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
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). 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.
You need to keep track of the values for each node and the starting Node
object itself, since this is a circular linked list. Your code for the Node
class may be different but it should be easy to modify the functions.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.