C# Program For Removing Duplicates From A Sorted Linked List
Last Updated :
10 Jan, 2023
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().
C#
// C# program to remove duplicates
// from a sorted linked list
using System;
public class LinkedList
{
// Head of list
Node head;
// Linked list Node
class Node
{
public int data;
public Node next;
public Node(int d)
{
data = d;
next = null;
}
}
void removeDuplicates()
{
// Another reference to head
Node current = head;
/* Pointer to store the next
pointer of a node to be deleted*/
Node next_next;
// Do nothing if the list is empty
if (head == null)
return;
// Traverse list till the last node
while (current.next != null)
{
// Compare current node with the
// next node
if (current.data == current.next.data)
{
next_next = current.next.next;
current.next = null;
current.next = next_next;
}
// Advance if no deletion
else
current = current.next;
}
}
// Utility functions
// Inserts a new Node at front
// of the list.
public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node 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
void printList()
{
Node temp = head;
while (temp != null)
{
Console.Write(temp.data + " ");
temp = temp.next;
}
Console.WriteLine();
}
// Driver code
public static void Main(String []args)
{
LinkedList llist = new LinkedList();
llist.push(20);
llist.push(13);
llist.push(13);
llist.push(11);
llist.push(11);
llist.push(11);
Console.WriteLine(
"List before removal of duplicates");
llist.printList();
llist.removeDuplicates();
Console.WriteLine(
"List after removal of elements");
llist.printList();
}
}
// This code is contributed by 29AjayKumar
OutputList 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)
Recursive Approach :
C#
// C# Program to remove duplicates
// from a sorted linked list
using System;
class GFG
{
// Link list node
public class Node
{
public int data;
public Node next;
};
// The function removes duplicates
// from a sorted list
static Node removeDuplicates(Node head)
{
/* Pointer to store the pointer
of a node to be deleted*/
Node 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 */
static Node push(Node head_ref,
int new_data)
{
// Allocate node
Node 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 */
static void printList(Node node)
{
while (node != null)
{
Console.Write(" " + node.data);
node = node.next;
}
}
// Driver code
public static void Main(String []args)
{
// Start with the empty list
Node 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);
Console.Write("Linked list before" +
" duplicate removal ");
printList(head);
// Remove duplicates from linked list
head = removeDuplicates(head);
Console.Write("Linked list after" +
" duplicate removal ");
printList(head);
}
}
// This code is contributed by PrinciRaj1992
OutputLinked list before duplicate removal 11 11 11 13 13 20Linked 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:
C#
// C# program to remove duplicates
// from a sorted linked list
using System;
class LinkedList
{
// Head of list
public Node head;
// Linked list Node
public class Node
{
public int data;
public Node next;
public Node(int d)
{
data = d;
next = null;
}
}
// Function to remove duplicates
// from the given linked list
void removeDuplicates()
{
// Two references to head temp
// will iterate to the whole
// Linked List prev will point
// towards the first occurrence
// of every element
Node 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.
public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node 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
void printList()
{
Node temp = head;
while (temp != null)
{
Console.Write(temp.data + " ");
temp = temp.next;
}
Console.WriteLine();
}
// Driver code
public static void Main(string []args)
{
LinkedList llist = new LinkedList();
llist.push(20);
llist.push(13);
llist.push(13);
llist.push(11);
llist.push(11);
llist.push(11);
Console.Write("List before ");
Console.WriteLine("removal of duplicates");
llist.printList();
llist.removeDuplicates();
Console.WriteLine(
"List after removal of elements");
llist.printList();
}
}
// This code is contributed by rutvik_56
OutputList 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:
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
public class Node
{
public int data;
public Node next;
public Node()
{
data = 0;
next = null;
}
}
public class GFG
{
/* Function to insert a node at
the beginning of the linked list */
static Node push(Node head_ref,
int new_data)
{
// Allocate node
Node 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 */
static void printList(Node node)
{
while (node != null)
{
Console.Write(node.data + " ");
node = node.next;
}
}
// Function to remove duplicates
static void removeDuplicates(Node head)
{
Dictionary<int, bool> track =
new Dictionary<int, bool>();
Node temp = head;
while(temp != null)
{
if(!track.ContainsKey(temp.data))
{
Console.Write(temp.data + " ");
track.Add(temp.data , true);
}
temp = temp.next;
}
}
// Driver Code
static public void Main ()
{
Node 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);
Console.Write(
"Linked list before duplicate removal ");
printList(head);
Console.Write(
"Linked list after duplicate removal ");
removeDuplicates(head);
}
}
// This code is contributed by rag2127
OutputLinked list before duplicate removal 11 11 11 13 13 20 Linked list after duplicate removal 11 13 20
Time Complexity: O(Number of Nodes)
Auxiliary Space: O(Number of Nodes)
Please refer complete article on Remove duplicates from a sorted linked list for more details!
Similar Reads
C Program For Removing Duplicates From A Sorted Linked List
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-
5 min read
C# Program For Removing Duplicates From An Unsorted Linked List
Write a removeDuplicates() function that takes a list and deletes any duplicate nodes from the list. The list is not sorted. For example if the linked list is 12->11->12->21->41->43->21 then removeDuplicates() should convert the list to 12->11->21->41->43. Recommended:
4 min read
C Program to Remove Duplicates from Sorted Array
In this article, we will learn how to remove duplicates from a sorted array using the C program.The most straightforward method is to use the two-pointer approach which uses two pointers: one pointer to iterate over the array and other to track duplicate elements. In sorted arrays, duplicates are ad
4 min read
C Program For Reversing A Doubly Linked List
Given a Doubly Linked List, the task is to reverse the given Doubly Linked List. See below diagrams for example. (a) Original Doubly Linked List (b) Reversed Doubly Linked List Here is a simple method for reversing a Doubly Linked List. All we need to do is swap prev and next pointers for all nodes,
3 min read
C Program For Writing A Function To Delete A Linked List
Algorithm For C:Iterate through the linked list and delete all the nodes one by one. The main point here is not to access the next of the current pointer if the current pointer is deleted. Implementation: C // C program to delete a linked list #include<stdio.h> #include<stdlib.h> #includ
2 min read
C Program For Merge Sort For Doubly Linked List
Given a doubly linked list, write a function to sort the doubly linked list in increasing order using merge sort.For example, the following doubly linked list should be changed to 24810 Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Merge sort for singly linked l
3 min read
C Program For Removing Middle Points From a Linked List Of Line Segments
Given a linked list of coordinates where adjacent points either form a vertical line or a horizontal line. Delete points from the linked list which are in the middle of a horizontal or vertical line.Examples: Input: (0,10)->(1,10)->(5,10)->(7,10) | (7,5)->(20,5)->(40,5) Output: Linked
4 min read
C Program For Searching An Element In A Linked List
Write a function that searches a given key 'x' in a given singly linked list. The function should return true if x is present in linked list and false otherwise. bool search(Node *head, int x) For example, if the key to be searched is 15 and linked list is 14->21->11->30->10, then functi
4 min read
C Program for Bubble Sort on Linked List
Given a singly linked list, sort it using bubble sort. Input : 10->30->20->5 Output : 5->10->20->30 Input : 20->4->3 Output : 3->4->20 C // C program to implement Bubble Sort on singly linked list #include<stdio.h> #include<stdlib.h> /* structure for a node
3 min read
C Program For Finding Intersection Of Two Sorted Linked Lists
Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory â the original lists should not be changed. Example: Input: First linked list: 1->2->3->4->6 Second linked list be 2-
9 min read