/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param n int整型 * @return ListNode类 */ struct ListNode* removeNthFromEnd(struct ListNode* head, int n ) { struct ListNode* fast=head; struct ListNode* slow=head; struct ListNode* cur=head; //寻找倒数第n个结点-->slow while(n--) { fast =fast ->next; } while(fast) { fast =fast->next; slow =slow->next; } //如果slow为head,直接删除 if(slow==head) { cur=slow->next; free(slow); return cur; } //当solw不为head时,寻找slow前一个结点 while(cur->next != slow) { cur=cur->next; } cur->next=slow->next; free(slow); return head; }