+ 8
LinkedList Implementation - C++
I usualy code in Java but i tried making a Linkedlist in C++ this time.. I get many errors that i don't know why... i would like an explanation about why i need to make the Node attribute (Node next), a pointer: Node* next... why? and explanaion about the wrong things in my code.. thanks to the helpers.. :) https://code.sololearn.com/cA123a1A17a2
17 Answers
+ 3
Maybe Linked Lists are not the best place to learn about pointers, because of all the recursion that is going on. You should probably review the topic, it's hard to get your head around at first.
But maybe think of it this way: The compiler needs to figure out how large your class is, so it can reserve the right amount of space when you make a new Node. In your example, how large is `Node`?
Well, it consists of an int, and a Node. What is Node made of? Well, an int and a Node. What is Node made of? Well, and int and a Node...
You'd need infinite memory to construct your type.
Now, a pointer is just an address that references some already existing object from the heap.
class Node {
Node* next;
int val;
}
How large is this struct? Well, an int (4 bytes), and a pointer (basically also an int, 4-8 bytes)
No problems here.
+ 5
Martin Taylor I know.. I'm doing it as practice..
+ 2
Hey I think you made your code extremely slow, by trying to recurse to back of the LinkedList.
Instead store your last pushed node in a Node pointer(which is in private scope) and then when trying to add a element, just do
Node* newNode = new Node(key);
CurrentNode->next = newNode;
CurrentNode = CurrentNode->next;
in the else statement (if the head is nullptr, just init head and set CurrentNode to head
+ 1
Martin Taylor , you don't understand what I mean and you are pulling away from the subject..
I implement the LinkedList in order to practice the C++ concepts (classes, recursion etc)...
Please read my original question and help me if you wish so... :)
+ 1
Schindlabua wow, that's a clever way to solve that problem then...
So in Java for example, is the Node attribute being converted to a pointer (memory address) ?
+ 1
Yahel I'm not a java dev and I get my languages confused, but I think in java *everything* is a pointer. As soon as you make a new object you only get to have a pointer to an object, never "the object itself" as it were. Only the primitive types like int and bool etc. are passed by value.
Of course in Java you never deal with all this explicitly, but in C++ you must.
+ 1
Schindlabua Yeah, you are right. Thanks :)
+ 1
https://youtube.com/channel/UC8XQYuj_gYrG6qK0wNBpSuA
+ 1
0
https://code.sololearn.com/Ww44SEy8A3m7/?ref=app
0
c++