Lucas
Lucas

Reputation: 69

returning the index of element in list C++

It seems like very common question, but they are all asked in python. I would like to return index of the searched element in a list !not STL!

My function

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;
  }

}

Upvotes: 1

Views: 1001

Answers (1)

amr ras
amr ras

Reputation: 302

You need to declare i, and increment the count as you traverse the list:

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
}

In case you actually want to return the index as you've stated and not as the code suggests. It would look like this:

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

Upvotes: 2

Related Questions