How to remove duplicates from the sorted Linked List in Java. – IT Blog
IT Blog
Boris IT Expert

How to remove duplicates from the sorted Linked List in Java.

Boris~November 2, 2020 /Linked List

If you want to remove duplicates from the sorted linked list in Java, you should follow several steps. This solution works only if the linked list is sorted. The fundamental idea is to start the while loop until the next element is null. Compare the current element with the next one. If the values are the same, we need to change the “next” element of the current to the “next” element of the “next.” It sounds confusing because there are many “next” here, so let’s take a look at the schema and the code.

If you want to remove duplicates from the sorted Linked List (Java), follow these steps.

Main steps of removing duplicates:

//Going through the list until face last item 
while (selectedItem != null && selectedItem.next != null) 
//If selected item data and next item data are equal
  if (selectedItem.data == selectedItem.next.data) {
//Changing connection of selected item to the item after the next one and remove next item from the list
 selectedItem.next = selectedItem.next.next;
 } else {
 //Just move the selection to the next item in the list
                selectedItem = selectedItem.next;
 }

Detailed schema of removing.

remove duplicates from the sorted linked list in java

Code example:

 private void removeDupicatesFromList() {
//You need to create linked list first
        creatingLinkedList();

//Put out selection to the start of the list
        ListNode selectedItem = head;

//Going through the list until face last item
   while (selectedItem != null && selectedItem.next != null) {
//If selected item data and next item data are equal
            if (selectedItem.data == selectedItem.next.data) {
//Changing connection of selected item to the item after the next one and remove next item from the list
                selectedItem.next = selectedItem.next.next;
            } else {
 //Just move the selection to the next item in the list
                selectedItem = selectedItem.next;
            }
        }

 //Put out selection to the beginning of the list to iterate items for logging
        selectedItem = head;

        while (selectedItem != null) {
            //Showing data of each item in the logs
            Log.d("linkedList", "-> " + selectedItem.data);
            selectedItem = selectedItem.next;
        }
        Log.d("linkedList", "-> " + null);
    }

In this article, you figured out the easiest way to remove duplicates from the sorted linked list java.

Full code and more examples in my facebook group.

Useful links:

Leave Any Questions Related To This Article Below!