返回链表的元素

Return element of linked list

本文关键字:元素 链表 返回      更新时间:2023-10-16

请删除。

我想实现一个链表。不幸的是,我不确定我是否在正确的轨道上。

#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节点的原因。