为什么链表使用指针而不是将节点存储在节点内 [英] Why do linked lists use pointers instead of storing nodes inside of nodes

查看:21
本文介绍了为什么链表使用指针而不是将节点存储在节点内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前在 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 object,那么 sizeof(Node) 会是什么?它将是 sizeof(int) + 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆