从某位老师那里学来的一个比较巧妙地方法😸😸😸
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n ) {
// write code here
if(head==NULL) {
return head;
}
struct ListNode* p=head;
struct ListNode* pre=head;
struct ListNode* explore=head;
int count=0;
while(p!=NULL) {
count++;
p=p->next;
}
int index=count-n+1;
if(index==1) {
return head->next;
}
while(index>2) {
index--;
pre=pre->next;
}
pre->next=pre->next->next;
return head;
}