Find Nth last element in Linked List
Utilisateur anonyme
void find_nth_last_node(struct node * head) { struct node * fast; struct node * slow; slow = head; fast = head; int count = 0; while(fast->next) { fast = fast->next; count++; if(count == N) break; } while(fast->next) { slow = slow->next; fast = fast->next; } } there are total 5 nodes. in this list 2nd node from last is equal to 3rd node from first. which is (5 - 2)th node from the first. so we start fast node first and move it 2 times. (-2 part in above line) and then start slow node next and move slow and fast, till fast reached end of list. by the time fast has reached slow will be pointing to 3rd node or second from last.