Question

I'm trying to complete an assignment for my Data Structures course but I keep getting a segfault in one of my functions.

What I have this function doing is creating two new chains, one for even numbers and another for odds, incrementing through the original list, and populating the new chains based on whether or not the element is even or odd.

What I am stuck on is getting the last node from the odd chain to link to the beginning of the even chain, because the chains need to be linked together at the end of the function.

void chain :: oddAndEvenOrdering()
{
//This function reorders the list 
//such a way that all odd numbers precede all even numbers. 
//Note that for two odd (even) 
//numbers i and j, the ordering between 
//i and j should be intact after reordering.
// Create empty chain to store odds
chain *oddChain = new chain(100);
chainNode *oddNode = oddChain->firstNode;
// Create empty chain to store evens
chain *evenChain = new chain(100);

int countOdd = 0;
int countEven = 0;
for (int i = 0; i < listSize-1; i++)
{
    if (*this->get(i) % 2 == 0)
    {
        evenChain->insert(countEven, *this->get(i));
        countEven++;
    } else {
        oddChain->insert(countOdd, *this->get(i));
        oddNode = oddNode->next;
        countOdd++;
    }

}
chainNode *evenNode = evenChain->firstNode; 
oddNode->next = evenNode;

delete this;
this->firstNode = oddChain->firstNode;

}
Was it helpful?

Solution

This will most certainly produce an error:

delete this;
this->firstNode = oddChain->firstNode;

You delete this and then try to access its members.

OTHER TIPS

Your memory issue has already been addressed in Anton's answer, but you could avoid it completely if you implemented your container in such a way that is consistent with the standard library. For example:

std::vector<int> vec { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
std::partition(vec.begin(), vec.end(), [](int i)
{
    return i % 2;
});

This will put all of the odds at the start of the vector and all of the evens at the end.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top