Spyros Pikoulas
Spyros Pikoulas

Reputation: 23

C++ Linked List: variable issue

struct List
{
     Post *p;  //a random class
     List *next;    
};

and i use this to insert data

List *help;
help=(*leaf)->start; //leaf is a node where is the start of the list
while(help!=NULL)
    help=help->next;
help=new List;
help->p=new Post()
help->next=NULL

why this doesnt work?

sorry for my bad english and if this is too easy .. Thanks again

Upvotes: 2

Views: 27

Answers (1)

Rainer Schwarze
Rainer Schwarze

Reputation: 4755

Problem 1:

In your while loop you repeat while help is not NULL, so you leave the while loop when help is NULL. You want to keep the last node in the list. The last node is the one where help->next == NULL. So your while loop should look like this:

while (help->next != NULL)
   help = help->next;

Problem 2:

When you set help = new List(); you lose the reference to the last node in your list. help now contains your new List instance, but you cannot set it to the next entry of your last element in the linked list (the one you searched for in your while loop).

So you may continue with:

help->next = new List(); // allocate node and set it as next
help = help->next;       // now you can set help to the new node
help->p = new Post();
help->next = NULL;

Note: You should write your while loop with braces - otherwise you may get confused which part of the code is part of the loop and which is not. Eventually this is personal style, but I'd recommend it to beginners:

while (help->next != NULL) {
    help = help->next;
}

Upvotes: 1

Related Questions