【发布时间】:2015-05-08 09:08:57
【问题描述】:
好的,假设我们在 C++ 中有一个链表实现。此外假设节点是一个类,列表本身是一个类,它看起来像这样:
#include <iostream>
using namespace std;
class List;
class Node
{
private:
Node(char, Node*);
char data;
Node* next;
friend class List;
friend ostream& operator<<(ostream&, const List&);
};
class List
{
public:
List(int = 0);
List(const List&);
~List();
bool gotoBeginning();
bool gotoEnd();
bool gotoNext();
bool gotoPrior();
bool insert(char);
bool remove(char&);
bool empty() const;
bool full() const;
bool clear();
List& operator=(const List&);
friend ostream& operator<<(ostream&, const List&);
private:
Node* head;
Node* cursor;
};
#endif
假设列表为空。 此外,假设我们刚刚在列表中插入了一个新元素“z”,这意味着列表当前有 1 个节点。
我们来看看插入函数:
bool List::insert(char item)
{
if(empty())
{
Node* newNode = new Node(item, NULL);
head = cursor = newNode;
return true;
}
else
{
// I dont need to show this part because the above code will suffice
}
}
好的,所以我们都知道,类型为指向节点的指针的变量 newNode 被分配了包含已存储在堆上的节点的内存位置。
现在记住我们刚刚创建了一个新节点,假设传递给插入函数的项目是'z'
内存分配 堆栈堆 | | | | \|/ \|/ 512 902 内存地址 | -----| |--->|-----|-----| | 902 | | | 'z'|空| |--------|----| |-----|-----| newNode (no name/newNode) 变量名(无名称):因为在堆上分配的内存只能通过指针直接访问。
我遇到的问题是这个。 newNode 指针是否在堆栈上创建并分配了一些内存地址,如 512,如上所示? 还是该指针从未在堆栈上分配(因此只需删除上面的 512)并且仅指向在堆上创建的内存(902)?
我问的原因是因为插入函数内部 if 语句中的第二行代码将 newNode 分配给 head 和 cursor
这让我很困惑。头部和光标现在会包含地址 512 还是 902?
如果我们继续在插入函数中的 else 语句中编写代码,那么它看起来像这样:
bool List::insert(char item)
{
if(empty())
{
Node* newNode = new Node(item, NULL);
head = cursor = newNode;
return true;
}
else
{
Node* newNode = new Node(item, NULL);
cursor = cursor->next = newNode; // what is this line doing
return true;
}
return false;
}
那么cursor->next如何获取新节点的值,cursor也获取新节点的值。
是的,上面的函数运行良好,我在项目中得到了 A,所以所有代码都是正确的,但我提到的概念让我很困扰
【问题讨论】:
标签: c++