# LeetCode第19题之 Remove Nth Node From End of List

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.

#include <iostream>
#include <vector>
using namespace std;

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
//如果为空链表
{
}
//如果链表只有一个节点，且n为1
if (NULL == head->next && 1 == n)
{
return NULL;
}
--n;
while (n>0 && ptr)
{
ptr = ptr->next;
--n;
}
//ptr不为NULL，则存在第n个节点,且此时ptr指向第n个节点
if (ptr != NULL)
{
//这种情况表示待删除的节点为头节点
if (ptr->next == NULL)
{
delete tmp;
}
else
{
ListNode * pre = NULL;
//curr指针所指的节点到ptr指针所指的节点相距n个节点，将ptr移到指向最后一个节点时，此时curr节点指向倒数第n个节点
while(NULL != ptr->next)
{
ptr = ptr->next;
pre = curr;
curr = curr->next;
}
//此时curr指向倒数第n个节点，pre指向待删除节点的前一个节点
pre->next = curr->next;
delete curr;
}
}
}
};
int main()
{
ListNode * p = (ListNode*)malloc(sizeof(ListNode));
p->val = 2;
p->next = NULL;
Solution s;
while(ptr != NULL)
{
cout<<ptr->val<<'\t';
ptr = ptr->next;
}
cout<<endl;
return 0;
}

#### Remove Nth Node From End of List -- LeetCode

2014-02-23 23:39:11

#### LeetCode19——Remove Nth Node From End of List

2015-02-05 15:07:55

#### [LeetCode] 019. Remove Nth Node From End of List (Easy) (C++/Python)

2015-03-04 19:26:10

#### LeetCode:Remove Nth Node From End of List

2014-11-18 10:08:28

#### LeetCode 19 : Remove Nth Node From End of List (Java)

2015-12-01 20:02:39

#### （Java）LeetCode-19. Remove Nth Node From End of List

2016-05-31 00:00:58

#### [leetcode] 19. Remove Nth Node From End of List python实现【easy】

2016-06-14 21:50:21

#### 【LeetCode】19 Remove Nth Node From End of List （c++实现）

2015-07-22 10:29:58

#### 【LeetCode-面试算法经典-Java实现】【019-Remove Nth Node From End of List（移除单链表的倒数第N个节点）】

2015-07-22 07:24:29

#### LeetCode(19) Remove Nth Node From End of List

2013-12-18 14:30:51