Search⌘ K

Solution Review: Remove Duplicates

Understand how to efficiently remove duplicates in a doubly linked list by tracking node data with a dictionary and deleting repeated nodes. This lesson guides you through the process with Python code and detailed explanation, improving your skills in managing linked list data.

We'll cover the following...

In this lesson, we consider how to remove duplicates from a doubly linked list.

Implementation

Check out the code below:

Python 3.5
def remove_duplicates(self):
cur = self.head
seen = dict()
while cur:
if cur.data not in seen:
seen[cur.data] = 1
cur = cur.next
else:
nxt = cur.next
self.delete_node(cur)
cur = nxt

Explanation

In the method remove_duplicates, we will keep track of the duplicates using a Python dictionary which we declare on line 3. cur is set to self.head on line 2 to help us traverse ...