/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param n int整型 * @return ListNode类 */ ListNode* moveNthToEnd(ListNode* head, int n) { // write code here ListNode* dummpy = new ListNode(-1); dummpy->next = head; ListNode* pre = dummpy, *fast = dummpy; for (int i = 0; i < n; i++) { fast = fast->next; } while (fast->next) { pre = pre->next; fast = fast->next; } // 此时pre所指的位置为要换到最后的元素的前一个位置 // 如果要换的元素本身就是最后一个 if (pre->next == fast) { return dummpy->next; } // 记录尾部位置 ListNode* tail = fast; ListNode* cur = pre->next; pre->next = cur->next; tail->next = cur; cur->next = nullptr; return dummpy->next; } };