Created
March 17, 2014 02:03
-
-
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.
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
/** | |
* 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