E
E
ElinMyers2019-12-18 20:11:51
C++ / C#
ElinMyers, 2019-12-18 20:11:51

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

There is a list initialization function:
Node* init(string str)
{
  Node* item = new Node;
  item->word = str;
  item->next = NULL;
  return item;
}

Let's say the list is initialized (no problem with it), and I want to add a new element by calling the following function:
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;
}

According to the debugger:
A list is passed into a function and a new element is added, but after that function ends, the list becomes garbage.
This is what Main looks like:
int main()
{
  Node* head = NULL;

  head = init("One");

  AddNode(head, "Two");
  
  PrintList(head); // Функция печати списка

  return 0;
}

Sobsna question: when passing a list to a function, is it the same list or a new one that just won't be returned to the head pointer ? Do I need to return a list with return? How to implement it?
Whole code:
spoiler

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


Do not suggest creating a list with a class, I need to do just that. Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
towin, 2019-12-18
@ElinMyers

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 question

Ask a Question

731 491 924 answers to any question