## Description

https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/

Given a linked list, remove the *n*^{th} node from the end of list and return its head.

For example,

1 2 3 |
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.

## Explanation

We introduce a preDelete pointer first and place it at the beginning of the linked list.

- Move head pointer first so that the distance between preDelete and head pointer would be N nodes.
- Move head and preDelete pointer together until head is reaching to the end.
- Modify preDelete pointing node.next to the next node of the delete node.

## Video Tutorial

## Java Solution

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if (n <= 0) { return head; } ListNode dummy = new ListNode(0); dummy.next = head; ListNode preDelete = dummy; for (int i = 0; i < n; i++) { if (head == null) { return null; } head = head.next; } while (head != null) { preDelete = preDelete.next; head = head.next; } preDelete.next = preDelete.next.next; return dummy.next; } } |