In: Computer Science
Write a C++ code to insert the following numbers in
two Linked Lists. Insert numbers of first list in Linked List#1,
and numbers of second list in Linked List#2. Do not insert both
lists in a single Linked List.
List#1.
5, 78, 45, 23, 11, 89, 10, 78, 6, 99, 876, 5, 67,
13
List#2.
5, 89, 688, 52, 557, 953, 5, 7, 55, 35, 89, 99, 99, 6,
557, 89, 5, 99, 6, 2, 45, 12, 7, 6, 94, 93, 99, 67
After inserting numbers in linked lists. Write a
function to print only those numbers that appear in List#1 and more
than 2 times in List#2.
For example, the number “5” appears in List#1 and 3
times in List#2. So your code should print “5” and similar other
numbers.
#include <iostream>
using namespace std;
struct Node
{
int data;
struct Node *next;
};
void append(struct Node** head_ref, int new_data)
{
struct Node* new_node = (struct Node*) malloc(sizeof(struct
Node));
struct Node *last = *head_ref;
new_node->data = new_data;
new_node->next = NULL;
if (*head_ref == NULL)
{
*head_ref = new_node;
return;
}
while (last->next != NULL)
last = last->next;
last->next = new_node;
return;
}
void print_common_element(Node *head1,Node *head2){
while(head1){
int count = 0;
int search_element = head1->data;
Node *tmp = head2;
while(tmp){
if(tmp->data == search_element)
count++;
tmp = tmp->next;
}
if (count > 2)
printf("The number %d appears in list1 and more than twice in
list2\n",search_element);
head1 = head1->next;
}
}
int main()
{
//5, 78, 45, 23, 11, 89, 10, 78, 6, 99, 876, 5, 67, 13
struct Node* head1 = NULL;
append(&head1, 5);
append(&head1, 78);
append(&head1, 45);
append(&head1, 23);
append(&head1, 11);
append(&head1, 89);
append(&head1, 10);
append(&head1, 78);
append(&head1, 6);
append(&head1, 99);
append(&head1, 876);
append(&head1, 5);
append(&head1, 67);
append(&head1, 13);
//5, 89, 688, 52, 557, 953, 5, 7, 55, 35, 89, 99, 99, 6, 557, 89,
5, 99, 6, 2, 45, 12, 7, 6, 94, 93, 99, 67
struct Node* head2 = NULL;
append(&head2, 5);
append(&head2, 89);
append(&head2, 688);
append(&head2, 52);
append(&head2, 557);
append(&head2, 953);
append(&head2, 5);
append(&head2, 7);
append(&head2, 55);
append(&head2, 35);
append(&head2, 89);
append(&head2, 99);
append(&head2, 99);
append(&head2, 6);
append(&head2, 557);
append(&head2, 89);
append(&head2, 5);
append(&head2, 99);
append(&head2, 6);
append(&head2, 2);
append(&head2, 45);
append(&head2, 12);
append(&head2, 7);
append(&head2, 6);
append(&head2, 94);
append(&head2, 93);
append(&head2, 99);
append(&head2, 67);
print_common_element(head1,head2);
return 0;
}