Linked Lists

I'm trying to insert an item into a linked list. I used code that I wrote last year for a similar program, but the code doesn't want to work now. I keep getting a "bus error", and I believe that it has something to do with something being set to zero when it should be set to NULL.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
LinkedList::LinkedList()
{
    NodeType *curptr;

    firstptr = new NodeType;
    curptr = firstptr;
    curptr -> next = NULL;
    lastptr = NULL;
}

void LinkedList::InsertItemBack(void* newItem)
{
    NodeType* curptr = firstptr;
    while (curptr != NULL && curptr != 0)
    {
       curptr = curptr -> next;
    }

    curptr -> next = new NodeType;
    curptr = curptr -> next;
    curptr -> info = newItem;
    curptr -> next = NULL;
}


Any help will be appreciated, thanks! :)
cplusplus wrote:
In C++, NULL expands either to 0 or 0L.

What is the purpose of lastptr? shouldn't point to the last valid cell?
1
2
3
4
5
void LinkedList::InsertItemBack(T newItem)
{
    lastptr->next = new Nodetype(newItem);
    lastptr = lastptr->next;
}


I found this:
1
2
3
4
5
6
while (curptr != NULL && curptr != 0)
    {
       curptr = curptr -> next;
    }
//here curptr == NULL
    curptr -> next = new NodeType; // NULL -> next  == crash 

Last edited on
I noticed that it crashes right after the while loop, too. The question is, what can I do? How can I set the next link in the list to a new node?

//here curptr == NULL
curptr -> next = new NodeType; // NULL -> next == crash


I think you have found out the reason yourself. currptr == NULL and then you attempt to reference the -> next member of cuz it crashes.

If I understand correctly, you want to add a new node right AFTER the last node is it ? Then in your earlier while loop you should keep a prevPtr instead.

1
2
3
4
5
6
7
8
9
10
11
12
13
14

NodeType* curptr = firstptr;
NodeType* prevPtr = NULL;

while (curptr != NULL && curptr != 0)
{
  prevPtr = currPtr;  
  curptr = curptr -> next;
}
//here currptr = NULL but prevPtr point to the last node

if (prevPtr!=NULL) prevPtr->next = new NodeType;

...
1
2
while( curptr->next!=NULL ) //or just while( curptr->next )
    curptr = curptr->next;
However that's O(n). if you keep a reference to the last cell you can have O(1).
Topic archived. No new replies allowed.