返回列表C ++中元素的索引

似乎是一个非常普遍的问题,但是它们都是在python中被问到的。我想返回列表中搜索到的元素的索引!不是STL!

我的功能

void checkNode(LinkedList* head, int v)
{
LinkedList* p = head;
while (p != NULL) {
    if (p->data == v) {
        cout << ; // here should be answer i suppose
    }
    else {
        cout << -1;
    }

    p = p->next;
  }

}
0
投票

您需要声明i,并在遍历列表时增加计数:

void checkNode(LinkedList* head, int v)
{
LinkedList* p = head;
int i=0; // Declare i
while (p != NULL) {
    if (p->data == v) {
        cout << i; // output i
        return;
    }
    ++i; // Increment index counter
    p = p->next;
  }
  // we've searched through the entire list
  cout << -1; // not found
}