Site icon

Remove duplicate nodes from sorted singly linked list in java(example/ algorithm)

Fig 1: Single linked list containing duplicates

In a sorted linked list, all the duplicate elements must be lying adjacent to each others e.g. duplicates of 2 and 3 are lying together as shown in Fig 1.

Algorithm: remove duplicate elements/ nodes from a single linked list

Time complexity of algorithm is O(n).

Fig 2: Delete duplicate elements from single linked list

Once we are done, with the removal of duplicate elements from linked list, our resultant linked list will be reduced to Fig 3. The linked list does not contain any duplicate elements.

Fig 3: Single linked list with unique elements

Program – remove/delete duplicate nodes from sorted singly linked list in java.

1.) RemoveDuplicates Class:

The RemoveDuplicates class has following methods:

package org.learn.Question;

import org.learn.List.Node;

public class RemoveDuplicates {

	public static void removeDuplicates(Node head) {
		// first node to be inserted
		if (null == head) {
			System.out.println("Linked list is empty");
			return;
		}
		Node nextNode = null;
		while (head.next != null) {
			// check for duplicates
			// E.g 1->2->2->3
			if (head.data == head.next.data) {
				nextNode = head.next.next;
				// deleting next node...
				// let gc take care of it
				head.next = null;
				head.next = nextNode;
			} else {
				// no duplicate..move to next node
				head = head.next;
			}
		}
	}

	public static void insert(Node head, int data) {
		while (head.next != null)
			head = head.next;
		head.next = new Node(data);
	}

	public static void print(Node head) {
		while (head != null) {
			System.out.printf("%d ", head.data);
			head = head.next;
		}
		System.out.println("");
	}
}

2.) App Class:

We are performing following method in App class.

package org.learn.Client;

import org.learn.List.Node;
import org.learn.Question.RemoveDuplicates;

public class App {
	public static void main(String[] args) {
		int[] listData = { 1, 2, 2, 3, 3, 9 };
		Node head = new Node(listData[0]);
		for (int count = 1; count < listData.length; count++)
			RemoveDuplicates.insert(head, listData[count]);

		System.out.printf("Linked list is : ");
		RemoveDuplicates.print(head);

		RemoveDuplicates.removeDuplicates(head);
		System.out.printf("Linked list after removing duplicates : ");
		RemoveDuplicates.print(head);
	}
}

3.) Node Class:

package org.learn.List;

public class Node {
	public int data;
	public Node next;

	public Node(int num) {
		this.data = num;
		this.next = null;
	}
}

Output – remove or delete duplicate nodes from sorted singly linked list in java

Linked list is : 1 2 2 3 3 9
Linked list after removing duplicates : 1 2 3 9

Download Code – remove delete duplicate nodes sorted linked list java

Exit mobile version