c++ - c ++递归函数正常工作,但从0开始索引。需要它从1开始
问题描述
问题是索引从 0 开始,我该如何重写它以从 1 开始。
该函数使用递归
链表数组:
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 42 -> 10 -> 空
输入:getPosition(head,42);
输出:9
我想要的是:
输出:10
template <class T>
int getPosition(Node<T>* head, T element) {
//check for null
if (head == NULL){
return -1;
}
//continue if not null
else{
//if current elemnt does not equal wanted element
if(head-> data != element){
//temp var to iterate through using recursion
int temp = getPosition(head -> next,element);
//if temp is not equal to element, add 1 to temp
if (temp!= -1){
return temp+1;
}
//return -1 to keep loop going
else{
return -1;
}
}
//if element found, return 0
else{
return 0;
}
}
}
解决方案
推荐阅读
- python - 为列表列表中的每个列表映射一个函数
- python - 如何让 Pandas 从下一行开始在新列中创建 sumsum?
- mfc - MFC CImageList DeleteImageList() vs Remove()
- android - Android studio 线性布局问题:我应该如何在没有嵌套权重的情况下布局我的?
- python - 16位PNG的像素值20930不应该是灰色阴影吗?
- numpy - Python 向量没有列大小?/ Theta 初始化为全 0
- python - 如何在不手动下载模型的情况下访问/使用谷歌预训练的 Word2Vec 模型?
- c - 我的 Visual Studio 2015 找不到构建项目的基本依赖项
- git - git checkout -b dev remote_repo/dev 没有从远程获取所有提交
- c++ - 为什么 cout 输出内存地址不是字符串?