luzhipeng ce4ee54 Apr 25, 2019
0 contributors

### Users who have contributed to this file

131 lines (95 sloc) 2.59 KB

## 题目地址

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.

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.

Could you do this in one pass?

## 关键点解析

1. 链表这种数据结构的特点和使用

2. 使用双指针

## 代码

```/*
* @lc app=leetcode id=19 lang=javascript
*
* [19] Remove Nth Node From End of List
*
* https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/
*
* algorithms
* Medium (34.03%)
* Total Accepted:    360.1K
* Total Submissions: 1.1M
* Testcase Example:  '[1,2,3,4,5]\n2'
*
* Given a linked list, remove the n-th node from the end of list and return
*
* 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.
*
*
* Could you do this in one pass?
*
*/
/**
* function ListNode(val) {
*     this.val = val;
*     this.next = null;
* }
*/
/**
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function(head, n) {
let i = -1;
const noop = {
next: null
};

while (currentP1) {

if (i === n) {
currentP2 = currentP2.next;
}

if (i !== n) {
i++;
}

currentP1 = currentP1.next;
}

currentP2.next = ((currentP2 || noop).next || noop).next;