int sum=0;
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
if(head == NULL|| head ->next ==NULL){ //空表情况
//最后节点的计数记为1
sum++;
}else{
head ->next = removeNthFromEnd(head->next,n);
sum++;
}
if(sum == n){
//如是头节点。则返回下一个节点
return head->next;
}else{
//如不是,则直接返回当前节点
return head;
}
}
第二种:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int sum = getCurrentIndexFromLast(head,n);
if(sum == n){
return head->next;
}else{
return head;
}
}
int getCurrentIndexFromLast(ListNode* head,int n){
if(head->next == 0){
return 1;
}else{
int sum = getCurrentIndexFromLast(head->next,n);
if(sum == n){
ListNode * node = head->next;
head->next = node->next;
}
return sum + 1;
}
}
第三种方法:快慢指针+加哑节点
https://i-blog.csdnimg.cn/blog_migrate/cd702b31232182f01f23c2fdf18371ce.gif
//快漫之阵
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
struct ListNode dummy;
struct ListNode* fast= &dummy;
struct ListNode* low = &dummy;
dummy.next = head;
for(int i = 0; i< n; i++){
fast = fast ->next;
}
while(fast ->next!= NULL){
low = low ->next;
fast = fast->next;
}
low ->next = low ->next->next;
return dummy.next;
}
第三种:双指针