Open In App

Javascript Program For Removing Duplicates From A Sorted Linked List

Last Updated : 15 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Write a function that takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once. 
For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates() should convert the list to 11->21->43->60. 

Algorithm: 
Traverse the list from the head (or start) node. While traversing, compare each node with its next node. If the data of the next node is the same as the current node then delete the next node. Before we delete a node, we need to store the next pointer of the node 

Implementation: 
Functions other than removeDuplicates() are just to create a linked list and test removeDuplicates(). 

Javascript




<script>
// Javascript program to remove duplicates
// from a sorted linked list
     
// Linked list Node
class Node
{
    constructor(d)
    {
        this.data = d;
        this.next = null;
    }
}
     
// Head of list
let head = new Node();   
function removeDuplicates()
{
    // Another reference to head
    let curr = head;
  
    // Traverse list till the last node
    while (curr != null)
    {
        let temp = curr;
 
        /* Compare current node with the
           next node and keep on deleting
           them until it matches the current
           node data */
        while(temp!=null &&
              temp.data==curr.data)
        {
            temp = temp.next;
        }
 
        /* Set current node next to the next
           different element denoted by temp*/
        curr.next = temp;
        curr = curr.next;
    }
}
     
// Utility functions
  
// Inserts a new Node at front of the list.
function push(new_data)
{
    /* 1 & 2: Allocate the Node &
              Put in the data */
    let new_node = new Node(new_data);
   
    // 3. Make next of new Node as head
    new_node.next = head;
   
    // 4. Move the head to point to
    // new Node
    head = new_node;
}
     
// Function to print linked list
function printList()
{
    let temp = head;
    while (temp != null && temp.data)
    {
        document.write(temp.data+" ");
        temp = temp.next;
    }
    document.write("<br>");
}
     
// Driver code
push(20)
push(13)
push(13)
push(11)
push(11)
push(11)
     
document.write(
         "List before removal of duplicates ");
printList();
removeDuplicates();
document.write(
         "List after removal of elements ");
printList();
// This code is contributed by unknown2108
</script>


Output:

Linked list before duplicate removal  11 11 11 13 13 20
Linked list after duplicate removal  11 13 20

Time Complexity: O(n) where n is the number of nodes in the given linked list.

Auxiliary Space: O(1)

Recursive Approach :  

Javascript




<script>
// JavaScript Program to remove duplicates
// from a sorted linked list
 
// Link list node
class Node
{
    constructor(val)
    {
        this.data = val;
        this.next = null;
    }
}
 
// The function removes duplicates
// from a sorted list
function removeDuplicates(head)
{
    /* Pointer to store the pointer
       of a node to be deleted */
    var to_free;
 
    // Do nothing if the list is empty
    if (head == null)
        return null;
 
    // Traverse the list till last node
    if (head.next != null)
    {
        // Compare head node with next node
        if (head.data == head.next.data)
        {
            /* The sequence of steps is important.
               to_free pointer stores the next of head
               pointer which is to be deleted. */
            to_free = head.next;
            head.next = head.next.next;
            removeDuplicates(head);
        }
 
        /* This is tricky: only advance
           if no deletion */
        else
        {
            removeDuplicates(head.next);
        }
    }
    return head;
}
 
// UTILITY FUNCTIONS
// Function to insert a node at
// the beginning of the linked list
    
function push(head_ref, new_data)
{
    // Allocate node */
var new_node = new Node();
 
        /* put in the data */
        new_node.data = new_data;
 
        /* link the old list off the new node */
        new_node.next = (head_ref);
 
        /* move the head to point to the new node */
        (head_ref) = new_node;
        return head_ref;
    }
 
    /* Function to print nodes in a given linked list */
    function printList(node) {
        while (node != null) {
            document.write(" " + node.data);
            node = node.next;
        }
    }
 
    /* Driver code */
     
        /* Start with the empty list */
var head = null;
 
        /*
          Let us create a sorted linked list to
         test the functions Created linked list
          will be 11.11.11.13.13.20
         */
        head = push(head, 20);
        head = push(head, 13);
        head = push(head, 13);
        head = push(head, 11);
        head = push(head, 11);
        head = push(head, 11);
 
        document.write("Linked list before" +
        " duplicate removal <br/>");
        printList(head);
 
        /* Remove duplicates from linked list */
        head = removeDuplicates(head);
 
        document.write("<br/>Linked list after" +
        " duplicate removal <br/>");
        printList(head);
 
// This code is contributed by todaysgaurav
 
</script>


Output

Linked list before duplicate removal  11 11 11 13 13 20
Linked list after duplicate removal  11 13 20

Time Complexity: O(n), where n is the number of nodes in the given linked list.

Auxiliary Space: O(n), due to recursive stack where n is the number of nodes in the given linked list.

Another Approach: Create a pointer that will point towards the first occurrence of every element and another pointer temp which will iterate to every element and when the value of the previous pointer is not equal to the temp pointer, we will set the pointer of the previous pointer to the first occurrence of another node.

Below is the implementation of the above approach:

Javascript




<script>
// javascript program to remove duplicates
// from a sorted linked list
 
    // head of list
    var head;
 
    // Linked list Node
     class Node {
            constructor(val) {
                this.data = val;
                this.next = null;
            }
        }
      
 
    // Function to remove duplicates
    // from the given linked list
    function removeDuplicates() {
        // Two references to head
        // temp will iterate to the
        // whole Linked List
        // prev will point towards
        // the first occurrence of every element
        var temp = head, prev = head;
 
        // Traverse list till the last node
        while (temp != null) {
 
            // Compare values of both pointers
            if (temp.data != prev.data) {
                /*
                 * if the value of prev is not equal to the value of temp that means there are
                 * no more occurrences of the prev data. So we can set the next of prev to the
                 * temp node.
                 */
                prev.next = temp;
                prev = temp;
            }
            /* Set the temp to the next node */
            temp = temp.next;
        }
        /*
         * This is the edge case if there are more than one occurrences of the last
         * element
         */
        if (prev != temp) {
            prev.next = null;
        }
    }
 
    /* Utility functions */
 
    /* Inserts a new Node at front of the list. */
    function push(new_data) {
        /*
         * 1 & 2: Allocate the Node & Put in the data
         */
        var new_node = new Node(new_data);
 
        /* 3. Make next of new Node as head */
        new_node.next = head;
 
        /* 4. Move the head to point to new Node */
        head = new_node;
    }
 
    /* Function to print linked list */
    function printList() {
        var temp = head;
        while (temp != null) {
            document.write(temp.data + " ");
            temp = temp.next;
        }
        document.write("<br/>");
    }
 
    /* Driver program to test above functions */
     
        push(20);
        push(13);
        push(13);
        push(11);
        push(11);
        push(11);
 
        document.write("List before ");
        document.write("removal of duplicates<br/>");
        printList();
 
        removeDuplicates();
 
        document.write("List after removal of elements<br/>");
        printList();
 
// This code contributed by aashish1995
</script>


Output

List before removal of duplicates
11 11 11 13 13 20 
List after removal of elements
11 13 20 

Time Complexity: O(n) where n is the number of nodes in the given linked list.
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Another Approach: Using Maps

The idea is to push all the values in a map and printing its keys.

Below is the implementation of the above approach:

Javascript




<script>
 
// Javascript program for the above approach
class Node
{
    constructor()
    {
        this.data = 0;
        this.next = null;
    }
}
 
/* Function to insert a node at
   the beginning of the linked
 * list */
function push(head_ref, new_data)
{
     
    /* allocate node */
    let new_node = new Node();
    
    /* put in the data */
    new_node.data = new_data;
      
    /* link the old list off
    the new node */
    new_node.next = (head_ref);
      
    /* move the head to point
    to the new node */
    head_ref = new_node;
    return head_ref;
}
 
/* Function to print nodes
in a given linked list */
function printList(node)
{
    while (node != null)
    {
        document.write(node.data + " ");
        node = node.next;
    }
}
 
// Function to remove duplicates
function removeDuplicates(head)
{
    let track = new Map();
    let temp = head;
      
    while(temp != null)
    {
        if (!track.has(temp.data))
        {
            document.write(temp.data + " ");
        }
        track.set(temp.data, true);
        temp = temp.next;
    }
}
 
// Driver Code
let head = null;
        
/* Created linked list will be
11->11->11->13->13->20 */
head = push(head, 20);
head = push(head, 13);
head = push(head, 13);
head = push(head, 11);
head = push(head, 11);
head = push(head, 11);
document.write("Linked list before duplicate removal ");
printList(head);
document.write("<br>Linked list after duplicate removal  ");
removeDuplicates(head);
 
// This code is contributed by patel2127
 
</script>


Output

Linked list before duplicate removal 11 11 11 13 13 20 
Linked list after duplicate removal 11 13 20 

Time Complexity: O(Number of Nodes)

Space Complexity: O(Number of Nodes)
 

Please refer complete article on Remove duplicates from a sorted linked list for more details!
 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads