Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ length()函数在链表中的实现_C++_Linked List - Fatal编程技术网

C++ length()函数在链表中的实现

C++ length()函数在链表中的实现,c++,linked-list,C++,Linked List,我正在实现一个链表,其中一个函数询问链表中的节点数。然而,正如需求所说,它需要递归地完成 这是我到目前为止的实现 class LList { public: bool isEmpty() const; void cons(int x); int length() const; private: struct Node { int item; Node* next; };

我正在实现一个链表,其中一个函数询问链表中的节点数。然而,正如需求所说,它需要递归地完成

这是我到目前为止的实现

class  LList {
    public:
       bool isEmpty() const;
       void cons(int x);
       int length() const;
    private:
       struct Node {
          int item;
          Node* next;
       };
       Node* head;
}

bool LList::isEmpty() const{
   if(head == nullptr)
       return true;
   else
      return false;
}
void LList::cons(int x){
   Node* temp = new Node;
   temp->item = x;
   temp->next = head;
   head = temp;
}
我只能用文字来做这件事,但不能让递归工作

int LList::length(Node* head) const{
    Node* temp = head;
    if (temp == nullptr) {
        return 0;
    }
    return 1 + length(temp->next);
}

int LList::length() const {
    return length(head);
}
我试图使用一个helper函数来完成这项工作,但它说声明与
int-LList::length()const


有人能帮我解决这个问题吗?

因为这听起来像是家庭作业,所以我要给你一些提示,而不仅仅是向你扔代码

您在错误的位置递归:您只有一个
LList
,因此在那里没有可递归的内容。相反,您要做的是在
节点
对象上递归


保留
int-LList::length()const
函数,但它所要做的就是检查
head
是否为
nullptr
,然后调用要生成的新递归函数:
int-LList::Node::length()const
。然后,这个循环通过
节点
对象的
下一个
指针递归,并对它们进行计数。

可能会有所帮助。但它没有任何参数。我真的不知道如何正确地重载这个函数是非常有问题的。考虑使用一个帮助函数,将一个<代码>节点*/COD>作为一个参数。您可以将一个<代码>私有< /代码>函数添加到可以从<代码>长度>代码>中调用的类吗?如果头是空的呢?它不会崩溃吗?当node->next不为null时,需要添加1,然后调用node length。当然,在实际工作中,您不会使用递归来实现这一点。在LList中添加或删除节点时,您需要维护一个长度变量。为什么不使用与STL容器的size()函数相同的length()返回类型?当C++程序员使用siz()时,为什么要命名它?不要重复Qt实现者所犯的错误。还有,为什么不使用empty()而不是isEmpty()…@molbdnilo OP在我写答案后更改了他的代码。现在看起来好多了,这(讽刺的是)让我的答案看起来更糟@我明白了。这个答案与原来的问题完全一致。