/** * 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 // 设置双指针,slow和fast // slow指向head结点前一个节点,fast指向head节点 // 先让fast向前移动n个节点,然后一同移动fast和slow节点 // 当fast节点到达链表末尾时将slow节点前的节点给删去 ListNode* node = new ListNode(-1); node->next = head; ListNode* fast = head; ListNode* slow = node; while(n-- && fast) fast = fast->next; while(fast && slow->next) { fast = fast->next; slow = slow->next; } slow->next = slow->next->next; return node->next; } };