Answer the question
In order to leave comments, you need to log in
How is a list passed to a function via a parameter?
Good day, I've been struggling with the task of creating a linked list for a long time, and I can't add elements.
The bottom line is that the element addition function works correctly, but as soon as the list function exits, it doesn’t seem to be ...
And so:
Here is the element structure:
struct Node
{
string word;
Node* next;
};
Node* init(string str)
{
Node* item = new Node;
item->word = str;
item->next = NULL;
return item;
}
void AddNode(Node* pfirst, string str)
{
Node *tmp, *item = new Node;
item->word = str;
item->next = NULL;
tmp = pfirst;
while (tmp->next != NULL)
tmp = tmp->next;
tmp->next = item;
delete tmp;
}
int main()
{
Node* head = NULL;
head = init("One");
AddNode(head, "Two");
PrintList(head); // Функция печати списка
return 0;
}
struct Node
{
string word;
Node* next;
};
Node* init(string str)
{
Node* item = new Node;
item->word = str;
item->next = NULL;
return item;
}
void AddNode(Node* pfirst, string str)
{
Node *tmp, *item = new Node;
item->word = str;
item->next = NULL;
tmp = pfirst;
while (tmp->next != NULL)
tmp = tmp->next;
tmp->next = item;
delete tmp;
}
void PrintList(Node* pfirst)
{
Node* tmp = pfirst;
while (true)
{
cout << tmp->word << endl;
if (tmp->next == NULL) break;
tmp = tmp->next;
}
}
int main()
{
Node* head = NULL;
head = init("One");
AddNode(head, "Two");
return 0;
}
Answer the question
In order to leave comments, you need to log in
Everything is correct except that you do not need to call
AddNode () in the function. This is how you remove the penultimate element of the list, and you don't need to do that.
You don't need to return anything from AddNode, you pass a pointer to it as parameters, and modify the structure it points to.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question