Remove duplicates from unsorted linked list in c
C program for Remove duplicates from unsorted linked list. Here problem description and explanation.
/*
C program for
Delete duplicate nodes in unsorted linked list
*/
#include <stdio.h>
#include <stdlib.h>
// Linked List LinkNode
struct LinkNode
{
int data;
struct LinkNode *next;
};
// Singly linked list
struct SingleLL
{
struct LinkNode *head;
struct LinkNode *tail;
};
// Returns the new linked list
struct SingleLL *newLinkedList()
{
// Create new linked list
struct SingleLL *sll = (struct SingleLL *)
malloc(sizeof(struct SingleLL));
if (sll == NULL)
{
printf("Memory overflow\n");
}
else
{
sll->head = NULL;
sll->tail = NULL;
}
return sll;
}
// Handles the request of adding new node at end of linked list
void addNode(struct SingleLL *sll, int data)
{
// Create dynamic node
struct LinkNode *node = (struct LinkNode *)
malloc(sizeof(struct LinkNode));
if (node == NULL)
{
printf("Memory overflow to Create LinkNode\n");
return;
}
else
{
// Set initial node value
node->data = data;
node->next = NULL;
}
if (sll->head == NULL)
{
sll->head = node;
}
else
{
sll->tail->next = node;
}
sll->tail = node;
}
// Display linked list element
void display(struct LinkNode *node)
{
if (node == NULL)
{
return;
}
struct LinkNode *temp = node;
// iterating linked list elements
while (temp != NULL)
{
printf(" %d →", temp->data);
// Visit to next node
temp = temp->next;
}
printf(" NULL\n");
}
void removeNode(struct SingleLL *sll)
{
if (sll->head == NULL)
{
// When linked list empty
return;
}
else
{
// Auxiliary variable
struct LinkNode *temp = sll->head;
struct LinkNode *hold = NULL;
struct LinkNode *initial = NULL;
struct LinkNode *current = NULL;
// Outer loop
while (temp != NULL)
{
current = temp;
sll->tail = current;
initial = current->next;
// Inner loop
// Remove all node which value is similar to temp node
while (initial != NULL)
{
if (temp->data == initial->data)
{
// Get remove node
hold = initial;
}
else
{
current = initial;
}
// Visit to next node
initial = initial->next;
if (hold != NULL)
{
// remove node
current->next = initial;
free(hold);
hold = NULL;
}
}
// Visit to next node
temp = temp->next;
}
}
}
int main(int argc, char
const *argv[])
{
struct SingleLL *sll = newLinkedList();
// Sorted Linked list node
addNode(sll, 1);
addNode(sll, 2);
addNode(sll, 9);
addNode(sll, 4);
addNode(sll, 9);
addNode(sll, 3);
addNode(sll, 1);
addNode(sll, 7);
addNode(sll, 2);
addNode(sll, 1);
printf(" Before Delete \n");
display(sll->head);
removeNode(sll);
printf(" After Delete \n");
display(sll->head);
return 0;
}
Output
Before Delete
1 → 2 → 9 → 4 → 9 → 3 → 1 → 7 → 2 → 1 → NULL
After Delete
1 → 2 → 9 → 4 → 3 → 7 → NULL
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment