/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
if(head == NULL || n <= 0)
return head;
struct ListNode* first = head;
struct ListNode* second = head;
struct ListNode* pre = NULL;
for(int i = 0; i < n - 1; i++) // 中间间隔N-1的距离
first = first->next;
while(first->next)
{
pre = second; // pre是倒数第k个节点的前一个节点,用来删除
second = second->next; // second是倒数第k个节点
first = first->next;
}
if( !pre ) // 如果倒数第k个节点就是head,那么pre会保留原来的NULL,这时head直接是倒数第k个节点second的下一个节点
head = second->next;
else
pre->next = second->next;
return head;
}