居然一次AC了,虽然是道极水的题。考虑好一些特殊条件,比如n小于等于0, root等于NULL即可。
ListNode *removeNthFromEnd(ListNode *head, int n) { // Start typing your C/C++ solution below // DO NOT write int main() function if(n <= 0 || head == NULL) return head; int len = 0; ListNode *tmp = head; while(tmp != NULL){ len++; tmp = tmp->next; } if(n > len) return head; if(n == len) return head->next; len = len - n; tmp = head; while(len > 1){ len--; tmp = tmp->next; } tmp->next = tmp->next->next; return head; }