//C快慢指针 struct ListNode* removeNthFromEnd(struct ListNode* head, int n) { struct ListNode* dummy = malloc(sizeof(struct ListNode)); dummy->val = 0, dummy->next = head; struct ListNode* first = head; struct ListNode* second = dummy; for (int i = 0; i < n; ++i) { first = first->next; } while (first) { first = first->next; second = second->next; } second->next = second->next->next; struct ListNode* ans = dummy->next; free(dummy); return ans; }
//C递归 struct ListNode* recursion(struct ListNode* head, int* n){ if(head->next==NULL) return head; recursion(head->next,n); if(--(*n)==0) head->next=head->next->next; return head->next; } struct ListNode* removeNthFromEnd(struct ListNode* head, int n){ struct ListNode* root=(struct ListNode*)calloc(sizeof(struct ListNode),1); root->next=head; return recursion(root, &n); }