Question

I am trying to work on pointers. I am under a situation that i want to traverse the linked list after the second node(from third node).

I have the basic idea to traversing the linked list is:

while(temp!=NULL)
{
 temp=temp->next;
} 

So what i want is this linked list must start from third position. Could anyone please help me in preparing logic for that? I am not interested in any using any in-built functions. I will use this logic in other application.

Était-ce utile?

La solution

If your list is temp then temp is also the first element.

Then temp->next will be second element, and temp->next->next will be the third.

So if you write

temp = temp->next->next;

temp will be pointing to the third element and you can start your traverse from there.

Autres conseils

Node *nth(Node *head, int nth){//nth : 0 origin
    while(nth && head){
        --nth;
        head = head->next;
    }
    return head;
}
...
Node *third = nth(head, 2);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top