Skip to content

Instantly share code, notes, and snippets.

@jones
Created January 1, 2015 21:36
Show Gist options
  • Save jones/a4cb63a15f65e541721b to your computer and use it in GitHub Desktop.
Save jones/a4cb63a15f65e541721b to your computer and use it in GitHub Desktop.
Given a singly-linked list, devise a time and space efficient algorithm to find the mth-to-last element of the list. Implement your algorithm, taking care to handle relevant error conditions. Define mth to last such that when m = 0, the last element of the list is returned.
Element *findMToLastElement( Element *head, int m ) {
if (!head || n < 0) {
return NULL;
}
Element *first, *second = head, head;
for(int i = 0; i < m; i++) {
first = first->next;
if (!first) {
return NULL;
}
}
while(first->next) {
first = first->next;
second = second->next;
}
return second;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment