Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (55.6k points)

Can anyone tell me how to remove duplicates in linked list in Python?

1 Answer

0 votes
by (119k points)

You can use this Python program to remove duplicates in linked list.

class Node:

    def __init__(self, data):

        self.data = data

        self.next = None

class LinkedList:

    def __init__(self):

        self.head = None

        self.last_node = None

 

    def append(self, data):

        if self.last_node is None:

            self.head = Node(data)

            self.last_node = self.head

        else:

            self.last_node.next = Node(data)

            self.last_node = self.last_node.next

 

    def get_prev_node(self, ref_node):

        current = self.head

        while (current and current.next != ref_node):

            current = current.next

        return current

 

    def remove(self, node):

        prev_node = self.get_prev_node(node)

        if prev_node is None:

            self.head = self.head.next

        else:

            prev_node.next = node.next

 

    def display(self):

        current = self.head

        while current:

            print(current.data, end = ' ')

            current = current.next

def remove_duplicates(llist):

    current1 = llist.head

    while current1:

        data = current1.data

        current2 = current1.next

        while current2:

            if current2.data == data:

                llist.remove(current2)

            current2 = current2.next

        current1 = current1.next

a_llist = LinkedList()

 

data_list = input('Enter the elements for the linked list: ').split()

for data in data_list:

    a_llist.append(int(data))

 

remove_duplicates(a_llist)

print('The list with duplicates removed: ')

a_llist.display()

I recommend enrolling in this Python Certification Course by Intelllipaat to learn Python.

Also, you can watch this video on linked list in Python:

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 30, 2020 in Python by Sudhir_1997 (55.6k points)
0 votes
1 answer
asked Oct 30, 2020 in Python by Sudhir_1997 (55.6k points)
0 votes
1 answer

Browse Categories

...