• Remove Nth Node From End of List

Remove Nth Node From End of List

Given a linked list, remove the nth node from the end of list and return its head.
For example,
1. Given linked list: 1->2->3->4->5, and n = 2.
2. 3. After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.
Solution:
1. /*
2. * Definition for singly-linked list.
3. * public class ListNode {
4. * int val;
5. * ListNode next;
6. * ListNode(int x) { val = x; }
7. * }
8.
/
9. public class Solution {
10. public ListNode removeNthFromEnd(ListNode head, int n) {
11. ListNode slow = head, fast = head;
12. 13. while (n-- > 0)
14. fast = fast.next;
15. 16. if (fast == null)
17. return head.next;
18. 19. while (fast != null && fast.next != null) {
20. slow = slow.next;
21. fast = fast.next;
22. }
23. 24. slow.next = slow.next.next;
25. 26. return head;
27. }
28. }