A ‘C’ program to create two singly linked lists and perform the intersection operations on two lists and display the resultant list.
Singly linked lists operations
#include#include /* Link list node */ struct node { int data; struct node * next; }; /* A utility function to insert a node at the begining of a linked list*/ void push(struct node ** head_ref, int new_data); /* A utilty function to chec if given data is present in a list */ int isPresent(struct node * head, int data); /* Function to get union of two linked lists head1 and head2 */ /* Function to get intersection of two linked lists head1 and head2 */ struct node * getIntersection(struct node * head1, struct node * head2) { struct node * result = NULL; struct node * t1 = head1; // Traverse list1 and search each element of it in list2. If the element // is present in list 2, then insert the element to result while (t1 != NULL) { if (isPresent(head2, t1 - > data)) push( & result, t1 - > data); t1 = t1 - > next; } return result; } /* A utility function to insert a node at the begining of a linked list*/ void push(struct node ** head_ref, int new_data) { /* allocate node */ struct node * new_node = (struct node * ) malloc(sizeof(struct node)); /* put in the data */ new_node - > data = new_data; /* link the old list off the new node */ new_node - > next = ( * head_ref); /* move the head to point to the new node */ ( * head_ref) = new_node; } /* A utility function to print a linked list*/ void printList(struct node * node) { while (node != NULL) { printf(“ % d“, node - > data); node = node - > next; } } /* A utilty function that returns true if data is present in linked list else return false */ int isPresent(struct node * head, int data) { struct node * t = head; while (t != NULL) { if (t - > data == data) return 1; t = t - > next; } return 0; } void main() { /* Start with the empty list */ struct node * head1 = NULL; struct node * head2 = NULL; struct node * intersecn = NULL; int n, num, i; clrscr(); /*create a linked lits 10->15->5->20 */ printf(“\nEnter total number elements of first list: \n”); scanf(“ % d”, & n); for (i = 0; i < n; i++) { printf(“\nenter % d element: “, i + 1); scanf(“ % d”, & num); push( & head1, num); } printf(“\nEnter total number elements of second list: \n”); scanf(“ % d”, & n); for (i = 0; i < n; i++) { printf(“\nenter % d element: “, i + 1); scanf(“ % d”, & num); push( & head2, num); } intersecn = getIntersection(head1, head2); printf(“\n First list is\ n”); printList(head1); printf(“\n Second list is\ n”); printList(head2); printf(“\n Intersection list is\ n”); printList(intersecn); getch(); }
Output
Enter total number elements of first list :
5
enter 1 element : 3
enter 2 element : 6
enter 3 element : 9
enter 4 element : 12
enter 5 element : 16
Enter total number elements of second list :
3
enter 1 element : 3
enter 2 element : 6
enter 3 element : 10
First list is
16 12 9 6 3
Second list is
10 6 3
Intersection list is
3 6
0 comments:
Post a Comment