# 数据结构与算法 | Leetcode 19. Remove Nth Node From

puppy-dog-cute-love-cat-mammal

## 删除单链表倒数第N个节点

Leetcode 19. Remove Nth Node From End of List

### 解法一

#### 思路

1. 先遍历一遍，求得整个链表的长度。
2. 再遍历一遍，当总长度`len`减去 `n` ，恰好等于循环的下标`i`时，就找到对应要删除的目标元素，将`prev`节点与`next`节点连接起来即可。

#### 代码

``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {

public ListNode removeNthFromEnd(ListNode head, int n) {
return null;
}
int len = 0;
for(ListNode curr = head ; curr != null;){
len++;
curr = curr.next;
}

if(len == 0){
return null;
}

if(len == n){
}

ListNode prev = null;
int i = 0;
for(ListNode curr = head; curr != null;){
i++;
prev = curr;
curr = curr.next;

if(i == (len - n)){
prev.next = curr.next;
}
}
}
}
``````

Leetcode测试的运行时间为`6ms`，超过了`98.75%`的java代码。

### 解法二

#### 代码

``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {

public ListNode removeNthFromEnd(ListNode head, int n) {
return null;
}
for(int i = 0; i < n; i++){
fast = fast.next;
}

if(fast == null){
return slow.next;
}

ListNode prev = null;
for(ListNode curr = slow; curr != null; ){
// when fast arrived at tail, remove slow.
if(fast == null){
prev.next =  curr.next;
break;
}
prev = curr;
curr = curr.next;
// move fast forward
fast = fast.next;
}