链表操作的段错误

Segfault on linked list manipulation

本文关键字:错误 段错误 操作 链表      更新时间:2023-10-16

我不知道为什么我在这里得到这个段错误。我试图取每一个其他节点,并把它放在一个新的列表。编辑:这是我结束了,但我仍然得到一个段故障

template <class T>
List<T> List<T>::mixSplit()
{
    List<T> newList;
    newList.length=0;
    for (int count=0;count<2;count++)
        newList.head=newList.head->next;
    newList.tail=tail;
    newList.head->prev=NULL;
    newList.tail->next=NULL;
    return newList;
}

的第一次迭代
for (int count=0;count<1;count++)
    newList.head=newList.head->next;

newList.headNULL…所以使用newList.head->next是一个坏主意。

我建议你相当正常地遍历当前列表(即:current = head; while(current) ...),在循环中增加计数器以跟踪列表中的当前位置,并且每当循环计数器为偶数或0 (counter % 2 == 0(counter & 1) == 0)时,使用标准的'list add'函数在新列表上添加新节点。