I'm working with LinkedLists from custom node, I'm still struggling to understand some concepts. For simplicity functions are reduced
class Node {
public:
T data;
Node* next;
Node(const T& copy){
data = copy;}
class T {
string name;
int age;
T(string name, int age){
T::name = name;
T:age = age;}
class LinkedList{
private:
Node* head;
void insertAtFront(string name,int age){
Node* newNode = new Node(name,age);
head = newNode;
/*
T temp(name,age);
Node newNode(temp);
head = &newNode */
;
}
I'm coming from java background, I know variables are treated differenly in c++ and java. I know c++ copies by value unless *, & is used. My misconceptions might probably occur because of the differences though, I couldn't solve it.
1-In insertAtFront function, implementations on the internet creates the node pointer dynamically(using new keyword). Can't we do it as the way between /* */ ?
2- I actually dont get the idea of why head is a pointer in the linked list. I've created linked lists in java. As long as the next value of the head is correct (so changing it in the correct way in c++) why should I make head a pointer ?
Node newNode(temp);
will be destroyed once the variable goes out of scope, so storing a pointer to it will lead to a dangling pointer