【问题标题】:operator [ ] recursion运算符 [ ] 递归
【发布时间】:2014-05-15 07:35:02
【问题描述】:

我需要帮助为链表的运算符 [] 创建递归定义。

LN 有一个 int 值和一个 next 指针

int & operator[] (int i, LN*l, int &k){
   int k = 0;
   //check if list is empty
   if(l == 0)
   return -1;
   //base case
   if(k == i)
   return l->value;
   else
   //I need to traverse through the linked list until I reach the ith position
   return operator[](i, l->next, ++k);
}

我在正确的轨道上吗?有没有办法可以消除 k 变量? //将其设为成员函数 假设有一个私有 LN* 头

 int & operator[](int &i){
    {
        LN* temp = head;
        if(i < 0 || temp ==0)
           return -1;
        if(i == 0)
           return temp->value;
        else{
           temp = temp->next;
           return operator[](--i);
        }

   }

【问题讨论】:

  • 你在这儿跟踪k,你注意到了吗?
  • 你为什么不能简单地减少 i 并检查它何时到达 0
  • 作为类的成员函数而不是将列表节点作为参数传递是否更有意义?
  • 您不应该将其实现为递归函数,因为它可以很容易地实现为循环。在大型列表中,如果您想迭代到高索引元素,您可能会用完堆栈

标签: c++ linked-list


【解决方案1】:

您可以通过在递归调用中与 l->next 一起传递 i-1 来摆脱 k(参数和局部变量)。那么当i 为 0 时,你就知道你想要当前的项目。

return operator[](i-1, l->next);

您还应该添加一些检查以确保 i 不小于零。

另请注意 - 递归在这里并没有真正的帮助,您可以更轻松地在循环中执行此操作。

【讨论】:

    【解决方案2】:

    我将它重写为:

    int & operator[] (int i, LN* l){
       if(i == 0) return l->value;
       else return operator[](i - 1, l->next);
    }
    

    即:递减i 变量,直到我们到达0(这意味着我们已经移动到下一个i 次)。

    此外,如果您想要 list[i] 的语法糖,您应该将其设为列表类的成员函数。

    附带说明,您应该使用 std::list&lt;int&gt;std::forward_list&lt;int&gt; 而不是创建自己的实现。

    最后,您应该注意到,一般来说,链表实际上并不意味着可以随机访问。您应该改为使用基于数组的容器。

    【讨论】:

    • 参数 l 可以有 head 作为默认值
    猜你喜欢
    • 2011-01-22
    • 1970-01-01
    • 2012-01-20
    • 2015-02-25
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多