Write a function that takes in a list of integers and returns a list containing
ID: 3848139 • Letter: W
Question
Write a function that takes in a list of integers and returns a list containing either all the odd numbers or all the even numbers in the list. The function should have two parameters: the list of integers, and a string (either ‘odd’ or ‘even’) that determines if the function should return all the odds or all the evens. If a user does not pass in a second argument (the string ‘even’ or ‘odd’), the function should default to returning all evens.
If there is something in the list that is not an integer, raise a ValueError and tell the user that this function can only take in lists of integers.
Explanation / Answer
#include<iostream>
using namespace std;
struct list
{
int data;
struct list * next;
};
struct list * even_odd_list(struct list * head,string s)
{
if(s=="odd")
{
struct list* t=head;
struct list* par=t;
while(t->next!=NULL)
{
if(t->data!=(int)t->data)
{
cout<<"Value Error!!"<<endl<<"Can accept only integer values";
return head;
}
if(!t->data&1)
{
struct list* temp=t;
par->next=t->next;
free(temp);
}
par=t;
t=t->next;
}
}
else
{
struct list* t=head;
struct list* par=t;
while(t->next!=NULL)
{
if(t->data!=(int)t->data)
{
cout<<"Value Error!!"<<endl<<"Can accept only integer values";
return head;
}
if(t->data&1)
{
struct list* temp=t;
par->next=t->next;
free(temp);
}
par=t;
t=t->next;
}
}
return head;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.