last nth element in a linked list
Anonymous
int getNthFromLast(Node *head, int n) { // Your code here Node*slow=head; Node*fast=head; while(--n and fast!=nullptr) { fast=fast->next; } if(fast==nullptr) { return -1; } while(slow!=nullptr and fast->next!=nullptr) { slow=slow->next; fast=fast->next; } return slow->data; }
Check out your Company Bowl for anonymous work chats.