Vanessa Larralde - 2 months ago 17

C++ Question

I'm trying to add items to the front of a list. Basically, what I'm trying to do here is:

-Start with a null list;

-Read a number;

-Call function where a new node is created to store the number, and next pointer points to null;

-If the list is empty, then this new node is the beginning of the list (and only element)

-If there are more elements, then this new node points to the head of the list and becomes the new head.

My function does what I want (at least I can see that in the debugger) but after it returns my list is empty and the head is null again.

`struct node{`

int data;

node *next;

};

void insert_front(node *list, int num){

node * newnode = new (node);

newnode->data = num;

newnode->next = nullptr;

if (list == nullptr)

list = newnode;

else{

newnode->next = list;

list = newnode;

}

}

int main()

{

int n;

node *head = nullptr;

cout << "Input numbers to store (0 finishes input): ";

cin >> n;

while (n != 0){

insert_front(head, n);

cin >> n;

}

return 0;

}

Also tried this but it doesn't even compile:

`void insert_front(node &lst, int num){`

node *newnode = new node();

newnode->data=num;

newnode->next=lst;

lst=newnode;

}

I intendedly avoided using OOP, templates, typedef, etc. as much as possible to get a "cleaner" code so I can understand how everything works.

Thanks :)

Answer

You need a reference to a pointer varibable: node* &list

```
void insert_front(node* &lst, int num){
node *newnode = new node();
newnode->data=num;
newnode->next=lst;
lst=newnode;
}
```

If you don't use a reference you'll be modifying a copy of your "lst" pointer, so the list will keep pointing to the old front after leaving this function. A reference parameter in c++ is prefixed with "&" symbol. In single old C (not your case) you'd need a pointer to a pointer instead.