# [LeetCode]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.

1. 初始化ListNode * t, p, q;

t = p = q = head;

2. 移动q，使q和p相差n-1个位置

3. 如果q不在倒数第1的位置，向后移动p和q，同时记录p的前一个结点t

4. 完成删除，返回结果

AC，Runtime: 36 ms

//LeetCode_Remove Nth Node From End of List
//Written by zhou
//2013.12.3

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {

ListNode *t, *p, *q;
t = p = q = head;

//调整q使p和q相差n-1,这样当p是倒数第n个时，q为倒数第1个
while(n-- != 1)
{
q = q->next;
}

//一直往后，直到q到达倒数第1个位置
while(q->next != NULL)
{
t = p;          //用t记录p的前一个
p = p->next;
q = q->next;
}

if (t == p) //要删除的为头结点
else
t->next = p->next;

}
};

• 本文已收录于以下专栏：

## [leetcode: Python]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 ...
• NXHYD
• 2017年05月19日 08:28
• 192

## LeetCode-19 Remove Nth Node From End of List(移除尾部第N个节点)

LeetCode-19 Remove Nth Node From End of List Given a linked list, remove the nth node from the end o...

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

## LeetCode: 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, ...
• wyc1230
• 2012年02月29日 00:47
• 717

## 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, ...

## LeetCode Remove Nth Node From End of List

Q: Given a linked list, remove the nth node from the end of list and return its head. For exam...

举报原因： 您举报文章：[LeetCode]Remove Nth Node From End of List 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)