Thursday, January 28, 2021

using 2 loops Remove duplicates from unsorted linked list

#include <iostream>

#include <bits/stdc++.h>

using namespace std;

struct node{

    int data;

    struct node* next;

};


//function to create  a new node

struct node* newnode(int data) //newnode is a pointer and data is its data

{

    node* temp= new node; temp->data=data;

    temp->next=NULL; return temp;

    

} //newnode ends



void remdup(node* start)

{

    struct node *ptr1, *ptr2, *dup;

    ptr1= start;  //put ptr1 on head

    while(ptr1!=NULL && ptr1->next!=NULL) //loop to pick element 1 by 1

    {

        ptr2= ptr1;

        while(ptr2->next!=NULL) //compare picked element with rest elements

        {

            if(ptr1->data==ptr2->next->data) //if duplicate then delete it

            {

                dup= ptr2->next;

                ptr2->next= ptr2->next->next;

                delete(dup);

                

            } //if ends

            else ptr2=ptr2->next;

            

           

        } //w ends

           ptr1= ptr1->next;

    } //w ends

    

    

} //fends


void printlist(node *node)

{

    while (node!=NULL)

    {

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

    } //w ends

    

} //f fends




int main() {

struct node *start= newnode(10);

 start->next = newnode(12);

    start->next->next = newnode(11);

    start->next->next->next = newnode(11);

    start->next->next->next->next = newnode(12);

    start->next->next->next->next->next =

                                    newnode(11);

    start->next->next->next->next->next->next =

                                    newnode(10);

 

  printlist(start); 

  remdup(start);

  printlist(start);

return 0;

}

 

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home