In: Computer Science
In C++, write a function that takes in as inputs two arrays, foo and bar, and their respective array sizes. The function should then output the concatenation of the two arrays as a singly linked list. You may assume that you are provided a singly linked list header file.
#include <iostream>
#include <cstdlib>
#include <limits.h>
using namespace std;
struct ListNode
{
int value;
struct ListNode *next;
};
void append(struct ListNode** head_ref, int new_data)
{
struct ListNode* new_node = (struct ListNode* ) malloc(sizeof(struct ListNode));
new_node->value = new_data;
struct ListNode *last = *head_ref;
if (*head_ref == NULL)
{
*head_ref = new_node;
return;
}
while (last->next != NULL)
last = last->next;
last->next = new_node;
return;
}
void printList(struct ListNode *node)
{
if(node == NULL){
cout<<"List is Empty\n";
return;
}
int count = 0;
while (node != NULL)
{
if(node->next!=NULL && node->next->value !=10)
cout<<node->value<<"-->";
else
cout<<node->value<<"-->NULL";;
node = node->next;
}
}
struct ListNode* concat(int *foo, int foosize, int *bar, int barsize){
struct ListNode* head = NULL;
for(int i = 0; i < foosize;++i)
append(&head, foo[i]);
for(int i = 0; i < barsize;++i)
append(&head, bar[i]);
return head;
}
int main()
{
int foo[] = { 5, 12, 32, 44, 72 };
int bar[] = { 1, 2, 3, 4, 5 };
struct ListNode* head = concat(foo,5,bar,5);
cout<<"Content of Linked list is: ";
printList(head);
return 0;
}
==========================================
SEE OUTPUT
Thanks, PLEASE COMMENT if there is any concern