我不知道为什么我会在这里遇到这个段错误。我正在尝试获取所有其他节点并将其放入新列表中。 编辑:这就是我最终得到的,但我仍然遇到段错误
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.head
是 NULL
...所以使用 newList.head->next
是个坏主意。
我建议您相当正常地遍历当前列表(即 current = head; while(current) ...
),在循环中增加一个计数器以跟踪当前位置列表,每当循环计数器为偶数或 0(counter % 2 == 0
或 (counter & 1) == 0
)时使用标准的“列表添加”在新列表上运行以附加新节点。
关于c++ - 链表操作的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7669204/