Q. Program to remove duplicate elements from a circular linked list.

Explanation

In this program, we will create a circular linked list and remove duplicate nodes from the list. We will compare a node with rest of the list and check for the duplicate. If the duplicate is found, delete the duplicate node from the list.

1->2->2->4->3

In the above list, we can see, node 2 is present twice in the list. So, we will have a node current that will iterate through the list. The index will point to next node to current. Temp will be pointing to the node previous to index. When a duplicate is found, we delete it by pointing temp.next to index.next. Above list after removing duplicates:

1->2->4->3

Algorithm

  1. Define a Node class which represents a node in the list. It has two properties data and next which will point to the next node.
  2. Define another class for creating the circular linked list and it has two nodes: head and tail.
  3. removeDuplicate() will remove duplicate nodes from the list:
    1. Node current will point to head and used to traverse through the list.
    2. The index will point to the next node to current and temp will point to previous node to index.
    3. We will compare the current.data with the index.data. If the match is found, delete duplicate data by pointing temp's next to index's next.
    4. Increment index to index.next and current to current .next.
    5. Repeat step from c to d till all the duplicates are removed.

Solution

Python

Output:

Originals list: 
 1 2 3 2 2 4
List after removing duplicates: 
 1 2 3 4

C

Output:

Originals list: 
 1 2 3 2 2 4
List after removing duplicates: 
 1 2 3 4

JAVA

Output:

Originals list: 
 1 2 3 2 2 4
List after removing duplicates: 
 1 2 3 4

C#

Output:

Originals list: 
 1 2 3 2 2 4
List after removing duplicates: 
 1 2 3 4

PHP

Output:

Originals list: 
 1 2 3 2 2 4
List after removing duplicates: 
 1 2 3 4

Next Topic#




Latest Courses