Challenge

Project 1 - Creation of user defined data type to implement the user interfaces for working with ‘Set’ (Mathematical Set theory) using Linked List

#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node *next;
};


struct Node *newNode(int data)
{
struct Node *temp = (struct Node*) malloc(sizeof(struct Node));
temp->data = data;
temp->next = NULL;
return temp;
}

void insert(struct Node **head, int data)
{
struct Node *temp = *head;
if (*head == NULL) {
*head = newNode(data);
return;
}
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode(data);
}


void displayList(struct Node *head)
{
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}

struct Node *findUnion(struct Node *head1, struct Node *head2)
{
struct Node *result = NULL;
struct Node *temp1 = head1;
struct Node *temp2 = head2;


while (temp1 != NULL) {
insert(&result, temp1->data);
temp1 = temp1->next;
}

while (temp2 != NULL) {
int flag = 0;
struct Node *temp = result;
while (temp != NULL) {
if (temp->data == temp2->data) {
flag = 1;
break;
}
temp = temp->next;
}
if (flag == 0) {
insert(&result, temp2->data);
}
temp2 = temp2->next;
}

return result;
}

int main()
{
struct Node *head1 = NULL;
struct Node *head2 = NULL;
struct Node *result = NULL;

insert(&head1, 1);
insert(&head1, 2);
insert(&head1, 3);
insert(&head1, 4);
insert(&head1, 5);

insert(&head2, 3);
insert(&head2, 4);
insert(&head2, 5);
insert(&head2, 6);
insert(&head2, 7);

printf("List 1: ");
displayList(head1);

printf("List 2: ");
displayList(head2);

result = findUnion(head1, head2);

printf("Union of the two lists: ");
displayList(result);

return 0;
}

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.