返回链表的元素
Return element of linked list
请删除。
我想实现一个链表。不幸的是,我不确定我是否在正确的轨道上。
#include <iostream>
using namespace std;
class Node {
friend class List;
public:
int value;
private:
Node *next;
};
class List {
public:
List ();
~List ();
Node * first() const;
Node * next(const Node * n) const;
void append (int i);
Node* head;
};
List::List() {
Node* head = new Node();
}
List::~List() {
while(head != NULL) {
Node * n = head->next;
delete head;
head = n;
}
}
Node * List::first() const {
return head; // this could also be wrong
}
Node * List::next(const Node * n) const {
return n + 1; // ERROR
}
void List::append(int i) {
Node * n = new Node;
n->value = i;
n->next = head;
head = n;
}
int main(void) {
List list;
list.append(10);
return 0;
}
当我尝试返回next()
中的元素时,我得到这个错误:
In member function ‘Node* List::next(const Node*) const’:|
error: invalid conversion from ‘const Node*’ to ‘Node*’ [-fpermissive]|
有人能帮帮我吗?
编辑:
我已经更新了错误行
我认为你要做的是返回节点的下一个:
Node * List::next(const Node * n) const {
return n->next;
}
如果这是一个每个对象的大小都是常量的数组,则可以使用指针算术,但链表不能使用指针算术。如果你有一个迭代器,你可以使用'++'操作符来获取下一个对象,但是在这种情况下,只返回节点的下一个字段。
我假设这也将工作,因为即使next被声明为私有,你已经使List为朋友。
您认为连续的节点位于连续的内存块中,而它们不是。链表的节点位于内存中的随机位置,这就是"next"指向next节点的原因。
相关文章:
- 打印所有链表的元素 (C++)
- 如何实现 Front() 方法以返回模板化双向链表C++的第一个元素?
- 在链链表中手动插入第五个元素
- 将数组的元素添加到链表中
- 为什么我在尝试在单向链表中打印元素时会出现这个永无止境的循环
- 如何将元素附加到链表?
- 仅显示链表的最后一个元素
- 从 c++ 中的链表中获取元素
- C++删除链表中的元素
- 我正在尝试计算链表中当前元素的数量
- 为什么将函数的返回类型从结构节点*更改为void后,链表的元素没有显示create_ll和显示?
- 如何从几乎排序的链表中分离放错位置的元素?
- 如何比较链表的元素?
- 链表 - 元素在删除后出现
- C++链表最后一个元素的迭代器?
- 如何找到双向链表的最大元素?
- 使用带有结构结构作为 C++; 元素的单向链表
- 如何检查单向链表的每个 3 个元素,然后删除其中一些元素?
- 将元素添加到 Head 的双链表
- 算法-统一随机元素链表