### 题目

Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.

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.

### 维护一个额外List，$O(n)$

#### 代码

/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
int size = ref.size();
if (size-1 < n) { return head; } // length < n
int prevIndex = size - n - 1; // find the previous element
ListNode prevNode = ref.get(prevIndex);
prevNode.next = prevNode.next.next;
return ref.get(0).next; // the 1st node after the sentinel
}
List<ListNode> result = new ArrayList<>();
ListNode sentinel = new ListNode(0); // sentinel
while (cursor != null) {
cursor = cursor.next;
}
return result;
}
}


### 不使用额外空间 $O(n)$

#### 代码

/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
// 不使用额外空间
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode sentinel = new ListNode(0);
ListNode slow = null, fast = sentinel;
int cursor = 0; // index of fast
while (fast != null) {
fast = fast.next;
if (slow != null) { slow = slow.next; }
if (cursor - n == 0) { slow = sentinel; } // slow和fast之间间隔n格距离
cursor++;
}
if (slow != null) {
slow.next = slow.next.next;
}
return sentinel.next;
}
}