c++ - 段错误 : 11 when trying to sort linked list by odds and evens

标签 c++ linked-list segmentation-fault nodes chain

我正在尝试完成我的数据结构类(class)的作业,但我的其中一个函数一直出现段错误。

我让这个函数做的是创建两个新链,一个用于偶数,另一个用于赔率,在原始列表中递增,并根据元素是偶数还是奇数来填充新链。

我坚持的是让奇数链的最后一个节点链接到偶数链的开头,因为链需要在函数末尾链接在一起。

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;

}

最佳答案

这肯定会产生错误:

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

您删除this,然后尝试访问其成员。

关于c++ - 段错误 : 11 when trying to sort linked list by odds and evens,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21418225/

相关文章:

c++ - 在 C++ 中减小大小/压缩 JSON 字符串

java - Java 中的引用是如何工作的?

C++强制编译时错误基于调用构造函数

c++ - 如何压缩备份日志文件?

c++ - 在 C++ 中创建类型列表组合

C Devoweler内存错误

c - 确保链接列表已释放

c++ - 当(CUDA 7.5 的)nvcc/cudafe++ 因段错误而崩溃时我该怎么办?

C++ 和 MySql++::段错误?

c - 尝试释放()链表节点会导致 C 中的段错误