(C++) Write a function that create a new linked list containing values from two
ID: 3680205 • Letter: #
Question
(C++) Write a function that create a new linked list containing values from two existing lists , in the same order as the two linked list.
/* Create union list if list1 contains 1 -> 3 -> 10 and list 2 contains 5 -> 3 -> 7 -> 2 this function returns a new list containing 1 -> 3 -> 10 -> 5 -> 3 -> 7 -> 2 while list1 and list2 are not changed */
IntNodeType * UnionList (IntNodeType * list1, IntNodeType * list2) {
//todo by you..
// Hint: Consider using two pointers, pointing to the first and current last node
// of the list that you are creating.
IntNodeType * head; //head of the new list you are creating
IntNodeType * tail; //pointing to the last node of the new list, so that newly
// created node can be easily just linked after this...
}
Explanation / Answer
Program fo linklisst is given below:
#include<stdio.h>
#include<stdlib.h>
struct IntNodeType
{
int data;
struct IntNodeType* next;
};
void pushListElement(struct IntNodeType** refer_head, int latest_data);
bool isPresent(struct IntNodeType *head, int data);
struct IntNodeType *UnionList(struct IntNodeType *head1, struct IntNodeType *head2)
{
struct IntNodeType *result = NULL;
struct IntNodeType *t1 = head1, *t2 = head2;
while (t1 != NULL)
{
pushListElement(&result, t1->data);
t1 = t1->next;
}
while (t2 != NULL)
{
if (!isPresent(result, t2->data))
pushListElement(&result, t2->data);
t2 = t2->next;
}
return result;
}
void pushListElement (struct IntNodeType** refer_head, int latest_data)
{
struct IntNodeType* new_IntNodeType =
(struct IntNodeType*) malloc(sizeof(struct IntNodeType));
new_IntNodeType->data = latest_data;
new_IntNodeType->next = (*refer_head);
(*refer_head) = new_IntNodeType;
}
void printList (struct IntNodeType *IntNodeType)
{
while (IntNodeType != NULL)
{
printf ("%d ", IntNodeType->data);
IntNodeType = IntNodeType->next;
}
}
bool isPresent (struct IntNodeType *head, int data)
{
struct IntNodeType *t = head;
while (t != NULL)
{
if (t->data == data)
return 1;
t = t->next;
}
return 0;
}
int main()
{
struct IntNodeType* linklisthead1 = NULL;
struct IntNodeType* linklisthead2 = NULL;
struct IntNodeType* unon = NULL;
pushListElement (&linklisthead1, 20);
pushListElement (&linklisthead1, 4);
pushListElement (&linklisthead1, 15);
pushListElement (&linklisthead1, 10);
pushListElement (&linklisthead2, 10);
pushListElement (&linklisthead2, 2);
pushListElement (&linklisthead2, 4);
pushListElement (&linklisthead2, 8);
unon = UnionList(linklisthead1, linklisthead2);
printf (" Contents of list 1 are: ");
printList (linklisthead1);
printf (" Contents of list 2 are: ");
printList (linklisthead2);
printf (" Union of list 1 and list 2 are: ");
printList (unon);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.