[TOP202]题解 | #调整牛群顺序#
调整牛群顺序
https://www.nowcoder.com/practice/a1f432134c31416b8b2957e66961b7d4
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
ListNode* moveNthToEnd(ListNode* head, int n) {
if (head == nullptr || n <= 0) {
return head;
}
ListNode* dummy = new ListNode(0); // 添加一个哑节点简化操作
dummy->next = head;
ListNode* slow = dummy;
ListNode* fast = dummy;
// 第一个指针先移动 n 步
for (int i = 0; i <= n; ++i) {
if (fast == nullptr) {
return head; // 链表长度小于 n,直接返回原链表
}
fast = fast->next;
}
// 同时移动两个指针,直到第一个指针到达链表末尾
while (fast != nullptr) {
slow = slow->next;
fast = fast->next;
}
// 此时第二个指针指向倒数第 n 个节点,将其从链表中删除
ListNode* nthNode = slow->next;
slow->next = nthNode->next;
// 将倒数第 n 个节点插入到链表末尾
ListNode* current = dummy;
while (current->next != nullptr) {
current = current->next;
}
current->next = nthNode;
nthNode->next = nullptr;
ListNode* newHead = dummy->next;
delete dummy; // 释放哑节点内存
return newHead;
}
};

查看11道真题和解析