Question:
Write a program to remove all duplicates from a singly linked list.
For example, if the list is
2-->4--->5--->7--->2---->5--->25--->2
after deletion, the output must be something like this
2-->4-->5-->7-->25
An easy solution would be to take one node at a time, compare its value with all the other nodes, and delete if there is a match. But that would be expensive.
A better solution is to sort the list and then compare adjacent values.
Here is how we do it.
For sorting the list, you can use any algorithm. Insertion sort is easiest for linked lists.
Let us look at the code.
We are starting from second node and comparing each node with its previous node. Initial value of prev_node is head and temp is second node. When the values are equal we are calling delete_nextnode() function which will delete the next node of prev_node. Then we move to next node, not using temp = temp->next but using temp = prevnode->next.
If there is no match, we just move to next node.
delete_nextnode() used here is a simple function, which deletes the next node of its parameter. Here is the code for it.
You can download the driver program from here.
Write a program to remove all duplicates from a singly linked list.
For example, if the list is
2-->4--->5--->7--->2---->5--->25--->2
after deletion, the output must be something like this
2-->4-->5-->7-->25
An easy solution would be to take one node at a time, compare its value with all the other nodes, and delete if there is a match. But that would be expensive.
A better solution is to sort the list and then compare adjacent values.
Here is how we do it.
- Take a sorted list
- Compare a node with its previous node.
- If they have same value, delete the node
- Move to next node
- Repeat steps 2 to 4 until end of list
For sorting the list, you can use any algorithm. Insertion sort is easiest for linked lists.
Let us look at the code.
void remove_duplicates(NODEPTR head) { head = sort_list(head); NODEPTR temp=head; NODEPTR prev_node = temp; temp = temp->next; while(temp!=NULL) { if(temp->n == prev_node->n) /* we have duplicate. Delete it*/ { delete_nextnode(prev_node); temp = prev_node->next; }else { prev_node = temp; temp = temp->next; } } }
We are starting from second node and comparing each node with its previous node. Initial value of prev_node is head and temp is second node. When the values are equal we are calling delete_nextnode() function which will delete the next node of prev_node. Then we move to next node, not using temp = temp->next but using temp = prevnode->next.
If there is no match, we just move to next node.
delete_nextnode() used here is a simple function, which deletes the next node of its parameter. Here is the code for it.
void delete_nextnode(NODEPTR temp) { if(temp->next) { NODEPTR d1 = temp->next; temp->next = temp->next->next; free(d1); } }
You can download the driver program from here.
Comments
Post a Comment