Skip to content

Instantly share code, notes, and snippets.

@manuel-sugawara
Created March 17, 2014 02:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manuel-sugawara/9592704 to your computer and use it in GitHub Desktop.
Save manuel-sugawara/9592704 to your computer and use it in GitHub Desktop.
Write a function to remove a single linked list's nth from last element.
/**
* Removes the list's nth from last element.
*/
public void removeNthFromLast(List list, int n) {
Node ahead = list.head;
for (int x = 0; x < n; x++) {
if (ahead.next == null) {
return null;
}
ahead = ahead.next;
}
// When deleting the first element take care to not lose the
// list head.
if (ahead.next == null) {
list.head = list.head.next;
return;
}
ahead = ahead.next;
Node prev = list.head;
while (ahead.next != null) {
ahead = ahead.next;
prev = prev.next;
}
prev.next = prev.next.next;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment