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.
链表基础题,让一前一后两个指针间隔出n的距离,那么先走的指针走到最后一个节点时,后走的指针就在倒数第n个节点。因为有可能删掉第一个节点,所以加一个头节点编码会方便一点
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(!head)return NULL;
ListNode* pHead=new ListNode(0);
pHead->next=head;
ListNode* l1=pHead;
ListNode* l2=pHead;
while(n--)l2=l2->next;
while(l2->next){
l1=l1->next;
l2=l2->next;
}
l1->next=l1->next->next;
return pHead->next;
}