开发者

Segfault on linked list manipulation

I dont know why im getting this segfault here. I am trying to take every other node and place it in a new list. Edit: this is what i ended up with but i still get a开发者_Go百科 segfault

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;
}


On the first iteration of

for (int count=0;count<1;count++)
    newList.head=newList.head->next;

...newList.head is NULL...so using newList.head->next is a bad idea.

I'd recommend that you iterate over the current list fairly normally(i.e. current = head; while(current) ...), increment a counter within the loop to track the current position in the list, and whenever the loop counter is even or 0 (counter % 2 == 0 or (counter & 1) == 0) use the standard 'list add' function on your new list to append a new node.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜