Why do linked lists use pointers instead of storing nodes inside of nodes

后端 未结 11 2200
春和景丽
春和景丽 2020-12-07 13:53

I\'ve worked with linked lists before extensively in Java, but I\'m very new to C++. I was using this node class that was given to me in a project just fine

         


        
11条回答
  •  难免孤独
    2020-12-07 14:23

    Why is it better to use pointers in a linked list?

    The reason is that when you create a Node object, compiler has to allocate memory for that object and for that the size of object is calculated.
    Size of pointer to any type is known to compiler and therefore with self referential pointer size of object can be calculated.

    If Node m_node is used instead then compiler has no idea about the size of Node and it will stuck in an infinite recursion of calculating sizeof(Node). Always remember: a class cannot contain a member of its own type.

提交回复
热议问题