0
linked list doesn't work
I am learning linked list from youtube. I tried to write a code to create a list like this https://code.sololearn.com/casfW7mGYbNC/#cpp Compilation is successful but it gives no output and I can't figure out why. Anybody helps? Many thanks
5 Réponses
+ 2
@Dragonxiv
Just because it prints something doesn't mean it is correct.
@Olivia
You aren't updating the head pointer.
You should realise that even pointers themselves are passed by value.
So if you make the pointer point somewhere else then that is NOT reflected outside the function.
There are 2 easy ways to fix it.
----
1: Pass the pointer by reference ( only in C++ )
void ist( Node* head,int pos,int d )
becomes
void ist( Node*& head,int pos,int d )
----
2: Return the new head
void ist( Node* head,int pos,int d )
becomes
Node* ist( Node* head,int pos,int d )
At the end of the function you then simply return head;
And when calling the function you assign it to head like this:
head = ist(head,1,2);
head = ist(head,2,5);
... etc
-----
Lastly there are a few situations you should deal with when using invalid positions.
For example a user or a drunk programmer can enter an index of 0 or -5 or something.
Or an index of 5 even though the list only has 1 element.
Also you are using C++, use C++ features.
replace printf with cout
replace all NULL with nullptr
0
Dennis I know that it dosnt mean its correct. I know that the output is still wrong, but i dont need to rewrite everything you did. I just wanted to give a start where Olivia can start debugging here code more easily. You still learn a lot by working on your code on your own. Not by reading a solution, except if you are compleatly stuck.
0
@Dragonxiv
Yes, but saying that he ( assuming gender here ) should start with
Node* head = new Node()
is just pointing ( hehe, get it ) him in the wrong direction.
But fine I removed a little bit of 'help'.
0
Thanks to all. I finally spot out my mistake: the insert function went wrong by having the first node pointing to the original address that the head pointer holds, which is null.
- 1
For a start you need to change your line: Node* head = NULL to : Node* head = new Node()
Then it starts printing out something.