为什么链表使用指针,而不是在节点内存储节点 [英] Why do linked lists use pointers instead of storing nodes inside of nodes
问题描述
在Java之前我已经使用过链接列表,但是我对C ++非常新。我使用的是一个项目中给我的这个节点类很好
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
class Node
{
public:
Node(int data);
int m_data;
Node *m_next;
};
但我有一个问题没有得到很好的答复。为什么需要使用
but I had one question that wasn't answered very well. Why is it necessary to use
Node *m_next;
指向列表中的下一个节点,而不是
to point to the next node in the list instead of
Node m_next;
我知道最好使用指针版本;我不打算争辩事实,但我不知道为什么会更好。我有一个不太清楚的答案,如何指针是更好的内存分配,我想知道如果有人在这里可以帮助我更好地理解。
I understand that it is better to use the pointer version; I'm not going to argue facts, but I don't know why it's better. I got a not so clear answer about how the pointer is better for memory allocation, and I was wondering if anyone here could help me understand that better.
推荐答案
这不只是更好,它是唯一可能的方式。
It's not just better, it's the only possible way.
如果你存储一个 Node
内部, sizeof(Node)
是什么?它会是 sizeof(int)+ sizeof(int)+ sizeof(Node)
,这将等于节点))
,这将等于 sizeof(int)+(sizeof(int)+(sizeof(int)+ sizeof(Node)))
等等到无穷大。
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.
这篇关于为什么链表使用指针,而不是在节点内存储节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!