linked list

I have a linked list and want to be able to access any element in the list by inputting an int. I have this code so far and want to know if i am going about it in the right manner.

1
2
3
4
5
6
7
8
9
10
11
12
ListElement *List::GetElement(unsigned int r){
    ListElement *current;
    unsigned int count = 0;
    
    if (r == count){
        while (r!=count){
            count++;
            current = current->next;
        }
        return current;
    }    
}

Last edited on
I don't understand what your first if at line 5 is for?

Also I think you probably need to initialise current to the first element in the list?
closed account (Lv0f92yv)
Yes - or this line: current = current->next; would segfault, because 'current' has not been initialized, and therefore cannot have a 'next' field.
Last edited on
Topic archived. No new replies allowed.