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>
/* structure of linked list */
struct node //node representation
{
int data;
struct node *next; // Pointer pointing towards next node
} *list_one, *list_two, *union_list, *intersection_list; // these are declared with node
void initialize()
{
list_one = list_two = NULL;
}
/*function to insert the data in linked list*/
void insert(struct node **head, int num)
{
struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = num;
newNode->next = *head; /*next of new node point to head node of linked list */
*head = newNode; /* making new node as new head of the linked list */
}
int search(struct node *head, int num) /* searching an element in linked list linearly from head to tail */
{
while(head != NULL)
{
if(head->data == num)
{
return 1;
}
head = head->next;
}
return 0;
}
/* union of the linked lists */
struct node* findunion(struct node *list_one, struct node *list_two)
{
union_list = NULL;
struct node *temp = list_one; /*adding all nodes of linked list 1 to union list */
while(temp != NULL)
{
insert(&union_list, temp->data);
temp = temp->next;
}
/* linked list 2 nodes are inserted which are not present in linked list 1 */
while(list_two != NULL)
{
if(!search(list_one, list_two->data))
{
insert(&union_list, list_two->data);
}
list_two = list_two->next;
}
return union_list;
}
/*intersection of linked lists */
struct node* intersection(struct node *list_one, struct node *list_two)
{
intersection_list = NULL;
/*search every element of list_one in list_two */
while(list_one != NULL)
{
if(search(list_two, list_one->data))
{
insert(&intersection_list, list_one->data);
}
list_one = list_one->next;
}
return intersection_list;
}
/* prints the list from the head node to tail node */
void printlinkedlist(struct node *nodeptr)
{
while(nodeptr != NULL)
{
printf("%d", nodeptr->data);
nodeptr = nodeptr->next;
if(nodeptr != NULL)
printf(",");
}
}
int main()
{
int i, list_oneCount, list_twoCount, temp;
initialize();
/* linked list 1 */
printf("enter number of nodes in linked list 1:\n");
fflush(stdout);
scanf("%d",&list_oneCount);
printf("enter %d integers \n", list_oneCount);
fflush(stdout);
for(i=0; i<list_oneCount; i++)
{
scanf("%d",&temp);
insert(&list_one, temp);
}
printlinkedlist(list_one);
printf("\nenter number of nodes in linked list2:\n");
fflush(stdout);
scanf("%d",&list_twoCount);
printf("enter %d integers \n", list_twoCount);
fflush(stdout);
for(i=0; i<list_twoCount; i++)
{
scanf("%d",&temp);
insert(&list_two, temp);
}
printlinkedlist(list_two);
findunion(list_one, list_two); /*union of given 2 linked lists*/
printf("\nunion linked list\n");
printlinkedlist(union_list);
intersection(list_one, list_two); /*intersection of 2 linked lists */
printf("\nintersection linked list\n");
printlinkedlist(intersection_list);
return 0;
}