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

后端 未结 11 2198
春和景丽
春和景丽 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 14:02

    It's not just better, it's the only possible way.

    If you stored a Node object inside itself, what would sizeof(Node) be? It would be sizeof(int) + sizeof(Node), which would be equal to sizeof(int) + (sizeof(int) + sizeof(Node)), which would be equal to sizeof(int) + (sizeof(int) + (sizeof(int) + sizeof(Node))), etc. to infinity.

    An object like that can't exist. It's impossible.

提交回复
热议问题