Skip to main content

Featured

functions in Python

C++ program to remove duplicate elements using linked list



Here is the program : 

#include <iostream.h>
#include <stdlib.h>

struct node {
int val;
struct node *link;
};

void display(struct node *head);
void remove(struct node *head);
struct node *create(struct node *head, int valu);

int main()
{
int max;
int valu;
int i;
struct node *head = NULL;

    cout<<"Enter the number of elements to be inserted : ";
cin >> max;

for (i = 0; i < max; i++) {
cin >> valu;
head = create(head, valu);

}

    cout<<"The original elements inserted are : ";
display(head);
remove(head);
cout<<"The elements after removal of duplicates : ";
display(head);

return 0;
}

struct node *create(struct node *head, int valu)
{
struct node *temp;
struct node *tmp;

tmp = (struct node *) malloc (sizeof (struct node));
tmp->val = valu;
tmp->link = NULL;

if (head == NULL) {
return tmp;
}
for (temp = head; temp->link != NULL; temp = temp->link) {

}

temp->link = tmp;
return head;
}

void display(struct node *head)
{
if (head != NULL) {
struct node *temp;
for (temp = head; temp != NULL; temp = temp->link) {
cout << temp->val << " ";
}
cout << endl;
}
}

void remove(struct node *head)
{
struct node *p;
struct node *temp, *h;
h = head;
while (h->link != NULL) {
p = h;
        while (p->link != NULL) {
            if (h->val == p->link->val) {
                temp = p->link;
                p->link = p->link->link;
                free(temp);
            } else {
                p = p->link;
            }
        }
        h = h->link;
    }
}

Comments

Post a Comment

Popular Posts