I used to do this years ago in good ol' Pascal but now I can't seem to be able to reproduce the same algorithm in C++. Actually, my function does what I want but it resets everything after it returns.
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.
I intendedly avoided using OOP, templates, typedef, etc. as much as possible to get a "cleaner" code so I can understand how everything works.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
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:
1 2 3 4 5 6 7
|
void insert_front(node &lst, int num){
node *newnode = new node();
newnode->data=num;
newnode->next=lst;
lst=newnode;
}
|
Thanks.