微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c++ 递归函数工作正常,但从 0 开始索引需要它从 1 开始

如何解决c++ 递归函数工作正常,但从 0 开始索引需要它从 1 开始

问题是索引从 0 开始,我该如何重写它以从 1 开始。

函数使用递归

链表数组:

1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 42 -> 10 -> NULL

输入: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;
      }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。