create a fuction to separate odd & even integers

67 views

Write the function READ, which is passed two double pointers pointing to the head pointers of two linked lists.

One list will hold even integers, the other one will hold odd integers. READ reads a series of integers. It separates adds odd integers to the first list, and even ones to the second, all in sorted order.

posted Apr 27, 2016

Try this

``````#include <iostream>
#include <list>

using namespace std;

// unary predicates implemented as classes
struct is_odd {
bool operator() (const int& value) { return (value%2)==1; }
};

struct is_even {
bool operator() (const int& value) { return (value%2)==0; }
};

// main with test data to make sure my function works
int main() {

list<double> odds;  // list for odds
list<double> evens; // list for evens

double myDoubles[] = {1, 5, 4, 6, 2, 3, 8, 7};  // test data
double moreDoubles[] = {11, 15, 14, 19, 9, 12}; // test data
odds.assign(myDoubles, myDoubles + 8);          // give first set of test data to odd list
evens.assign(moreDoubles, moreDoubles + 6);     // give second set of test data to even list

// printing of the odd list
for (auto &itr : odds) {
cout << itr << endl;
}

cout << endl;   // printing newline for neatness

// printing the even list
for (auto &itr : evens) {
cout << itr << endl;
}

return 0;

}

{
// look at each element in odd list
for (auto & itr: *odd) {
// if it is even
if ((int)itr % 2 == 0) {
// put that same value in the even list
even->push_back(itr);
}
}

// remove all evens from odd list
odd->remove_if(is_even());

// look at each element in the even list
for (auto & itr: *even) {
// if the element is odd
if ((int)itr % 2 == 1) {
// put that same value in the odd list
odd->push_back(itr);
}
}

// remove all odds from the even list
even->remove_if(is_odd());

// sort odd list
odd->sort();

// sort even list
even->sort();

}
``````
``````digitSum(9625, 'o')