Thursday, January 28, 2021

Recursive method to delete duplicates from list and print list

 #include <iostream>

#include <bits/stdc++.h>

using namespace std;


class node{

    public: int data; node* next;

    

};


void remdupli(node* head)

{

    node *tofree ; //pointer to store  pointer of node to be deleted

    if(head==NULL) return; //do nothing if list is empty

    if(head->next!=NULL) //traverse list to the last node

    {

        if(head->data==head->next->data) //compare head and next node

        {

            tofree=head->next; //tofree strores the next of headpointer to be delected

            head->next==head->next->next; //move headnext by 1 unit

            free(tofree); 

            remdupli(head);

        }

        

        else

        {

            remdupli(head->next); //only advance if no deletion

        } //else ends

    } //if ends

    

} // f ends



void push(node** head_ref, int new_data)

{

    node *new_node= new node();

    new_node->data= new_data;

    new_node->next= (*head_ref);

    (*head_ref)=new_node;


    

} //f ends



void printlist(node* node)

{

    while(node!=NULL)

    {

    cout<<node->data<<" ";

    node= node->next;

    } //while ends

} //f ends



int main() {

 node *head= NULL;

 push(&head, 20);

  push(&head, 13); 

    push(&head, 13); 

    push(&head, 11); 

    push(&head, 11); 

    push(&head, 11);  

    printlist(head); //list before duplicate removal

    remdupli(head); //method to remove duplicate

    printlist(head); //list after duplicate is removed

 


return 0;

}


0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home