使用快慢指针来解决,快指针比慢指针快n步,这样当快指针到链表尾时快指针刚才指向的是倒数的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) { // write code here ListNode* slow = head; ListNode* fast = head; //快指针先走n步; while(n--) { fast = fast->next; } if(fast == NULL) { ListNode *tmp = head->next; free(head); head = NULL; return tmp; }else { //快指针走到尾时,慢指针刚好是倒数第n个节点; while(fast->next) { slow = slow->next; fast = fast->next; } ListNode* tmp = slow->next; slow->next = slow->next->next; tmp->next = NULL; free(tmp); tmp = NULL; return head; } } };