主要思路:定义两个指针,先移动其中的一个指针,使得他们之间的差为n。之后就同时移动指针。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyHead=(ListNode*)malloc(sizeof(ListNode));
dummyHead->next=head;
ListNode* pre=dummyHead,*cur=head;
int count=0;
while(cur!=NULL){
if(count!=n){
count++;
}else{
pre=pre->next;
}
cur=cur->next;
}
pre->next=pre->next->next;
return dummyHead->next;
}
};