# [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;

};