Thursday, January 28, 2021

Remove duplicates from a sorted ll and print

#include <iostream>

#include <bits/stdc++.h>

using namespace std;


//take ll node

class node{

  public:  int data; node* next;

};


//function to rem duplicates from sorted list

void remdupli(node* head)

{

    node *current = head;  //current pointer points to head

    node *next_next;      //another pointer named next_next

    //next next pointer willl store the pointer of the node to be deleted

    

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

    

    //traverse the list till last node

    while(current->next!=NULL)

    {

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

       {

         next_next=current->next->next; 

         free(current->next); 

         current->next= next_next;

        

       } //iffends

       

       else {current=current->next;} //if duplicate not found, move pointer 

    } //while ends

} //f ends


//function to push nodedata

void push(node** head_ref, int new_data) // head_ref is a pointer, points to  head

{

    node* new_node= new node(); //new_node is a pointer 

    new_node->data= new_data; //its data is new data

    new_node->next= (*head_ref); //its next is head pointer

    (*head_ref) = new_node;   //head points to new node

    

} //push fends



void printlist(node* node)

{

    while(node!=NULL) //till there is a node 

    {

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

        node=node->next; //move poiinter by unit1

    } //w ends

    

} //f ends




int main() {

node *head= NULL; //make head pointer point to 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);   //function which removes the duplicate

printlist(head); //list after duplicate removed

return 0;

}


0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home