首页 > 解决方案 > 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;
      }
    }
}

标签: c++recursiondata-structureslinked-list

解决方案


推荐阅读