Solved programming problem

By traverse only ones Delete Duplicate From A single Linked List in C++.

Source code

#include <iostream>

using namespace std;

struct list

{

    int data;

    struct list *next;

};

typedef struct list node;

node *head;

void insert_node()

{

    node *temp=new node();

    cout<<"Data: ";

    cin>>temp->data;

    temp->next=NULL;

    if(head==NULL)

    {

        head=temp;

    }

    else

    {

        node *last=head;

        while(last->next != NULL)

        {

            last=last->next;

        }

        last->next=temp;

    }

}

void RemoveDuplicates()

{

    node *temp=head;

    while(temp->next != NULL)

    {

        if(temp->data==temp->next->data) /// if duplicate found

        {

            node *t1=temp->next;

            if(temp==head) ///if it is the 1st node

            {

                head->next = temp->next->next;

                delete(t1);

            }

            else ///for other node

            {

                temp->next = temp->next->next;

                delete(t1);

            }

            temp = temp;

        }

        else ///if its not a duplicate

        {

            temp=temp->next;

        }

    }

}

void print_node()

{

    node *temp=head;

    if(head==NULL)

    {

        cout<<"No Data Found";

    }

    else

    {

        while(temp!= NULL)

        {

            cout<<temp->data<<" ";

            temp=temp->next;

        }

    }

}

int main()

{

    int flag=1;

    cout<<"Insert Data Ascending Order: "<<endl;

    while(flag==1)

    {

        insert_node();

        cout<<"Press 1 to Insert Node 0 to Exit: ";

        cin>>flag;

    }

    cout<<"Your Linked List: ";

    print_node();

    RemoveDuplicates();

    cout<<"Your New Linked List: "<<endl;

    print_node();

    cout<<endl;

    return 0;

}

Output

Insert Data Ascending Order:
Data: 2
Press 1 to Insert Node 0 to Exit: 1
Data: 2
Press 1 to Insert Node 0 to Exit: 1
Data: 4
Press 1 to Insert Node 0 to Exit: 1
Data: 7
Press 1 to Insert Node 0 to Exit: 1
Data: 7
Press 1 to Insert Node 0 to Exit: 0
Your Linked List: 2 2 4 7 7
Your New Linked List:
2 4 7

Join the discussion

Add your comment