【发布时间】: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