Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Note:Given n will always be valid.
Try to do this in one pass.
ListNode *removeNthFromEnd(ListNode *head, int n) {
//此题要求比遍历一遍搞定,需要一个指针来指向删除节点的前面节点,对于删除头结点的情况需要特殊考虑, p -> next和q-> next节点的关系需要搞清楚
ListNode *p = head, *q = head;
while (n--)
q = q -> next;
if (q == NULL)
return p -> next;
while (q -> next)
{
p = p -> next;
q = q -> next;
}
p -> next = p -> next -> next;
return head;
}