Monday, 29 December 2014

Delete duplicate content from linked-list

The code given below is a code written in c++ . This code deletes all the duplicate contents of the linked-list . In the code there is a pointer(ptr) of type node which points  to a node . There is also a pointer pptr which  points to the previous node of ptr . Create function is used to insert elements in the linked-list by creating nodes . Display function is used to display the elements in the list . Let's talk about the delete_duplicate function , this function uses two loops both of which are while loops . First(outer) while loop is used to select an element using the temp pointer and set the values of ptr and pptr pointers . Then we check for duplicate content in the if clause of inner loop . The inner loop is used to compare all the other elements of the linked-list with the selected element . If the duplicate content is found then the particular node is deleted using the line  

pptr->link=ptr->link;
 ptr=ptr->link;

and the ptr is pointed to the next node without changing pptr . In the else clause the pptr pointer is made to point to the next node and so as ptr.


#include<iostream>
#include<conio.h>
using namespace std;
struct node
{
    int data;
    node *link;
}*head=NULL,*ptr,*temp,*pptr;

void create()
{
    int item;
    cout<<"enter the item you want to insert"<<endl;
    cin>>item;
    ptr=head;
    if (ptr==NULL)
    {
        ptr=new node;
        ptr->data=item;
        ptr->link=NULL;
        head=ptr;
    }
    else
    {
        ptr=new node;
        ptr->data=item;
        ptr->link=head;
        head=ptr;
    }
}

void delete_duplicate()
{
    temp=head;
    ptr=head->link;
    pptr=head;
    int d;
    while(temp!=NULL)
    {
        d=temp->data;
        ptr=temp->link;
        pptr=temp;
        while(ptr!=NULL)
        {
            if(d==ptr->data)
            {
                pptr->link=ptr->link;
                ptr=ptr->link;
            }
            else
            {
                pptr=ptr;
                ptr=ptr->link;
            }
        }
        temp=temp->link;
    }
}

void display()
{
    ptr=head;
    while(ptr!=NULL)
    {
        cout<<ptr->data<<"\t";
        ptr=ptr->link;
    }
}

int main()
{
    int option;
    while(option!=4)
    {
        cout<<endl;
        cout<<"enter 1 to enter the data in the list"<<endl;
        cout<<"enter 2 to display data "<<endl;
        cout<<"enter 3 to delete duplicate content from the list"<<endl;
        cout<<"enter 4 to exit "<<endl;
        cin>>option;
    switch(option)
    {
        case 1: create();
        break;
        case 2: display();
        break;
        case 3: delete_duplicate();
        break;
    }
    }
    getch();    return 0;
}

No comments:

Post a Comment