Created
January 1, 2015 21:36
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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