# 19. Remove Nth Node From End of List

**<font color=red>难度:Medium<font>**

## 刷题内容
> 原题连接

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

> 内容描述

```
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.
```

> 思路
******- 时间复杂度: O(n)******- 空间复杂度: O(1)******

删除倒数第n个数，为了防止链表长度为1时的空指针异常，先插入一个链表头，接着我们只要先遍历链表，计算出链表的总长度，再用总长度减去 n 就是我们要删除的数的前一个数距链表头的长度，接下来只要用个循环找到并删除要删除的节点即可。

```cpp
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
       ListNode* current = head;
        int num = 0;
        while(current)
        {
            num++;
            current = current ->next;
        }
        ListNode* n1 = new ListNode(0);
        n1 ->next = head;
        current = n1;
        num -= n;
        while(num)
        {
            num--;
            current = current ->next;
        }
        ListNode* temp = current ->next;
        current ->next = temp ->next;
        return n1 ->next;
    }
};
```