Answer to Question #238003 in C++ for Myname

Question #238003
Write a program to remove the duplicate elements from a sorted linked list.
1
Expert's answer
2021-09-16T13:01:21-0400


#include <iostream>
using namespace std;
 


class ListNode
{
    public:
    int item;
    ListNode* next;
};
 


void deleteDuplicates(ListNode * list)
{
   
    ListNode* currentNode = list;
 
    
    ListNode* next_next;
     
    
    if (currentNode == NULL)
    return;
 
    
    while (currentNode->next != NULL)
    {
    
    if (currentNode->item == currentNode->next->item)
    {
               
        next_next = currentNode->next->next;
        free(currentNode->next);
        currentNode->next = next_next;
    }
    else 
    {
        currentNode = currentNode->next;
    }
    }
}
 


void add(ListNode** head, int data)
{
    
    ListNode* node = new ListNode();
             
    
    node->item = data;
                 
    
    node->next = (*head);    
         
    
    (*head) = node;
}
 


void displayList(ListNode *node)
{
    while (node!=NULL)
    {
        cout<<" "<<node->item<<" ";
        node = node->next;
    }
}
 


int main()
{
    
    ListNode* list = NULL;
     
   
    add(&list, 1);
    add(&list, 13);
    add(&list, 13);
    add(&list, 1);
    add(&list, 11);
    add(&list, 12);                                    
 
    cout<<"The original linked list with duplicates:\n ";
    displayList(list);
 
    
    deleteDuplicates(list);
 
    cout<<"\nThe new linked list after removing duplicates:\n";    
    displayList(list);            
     
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS