[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;
    }
};


全部评论

相关推荐

不愿透露姓名的神秘牛友
03-28 13:48
hory权:校招vip纯神人了,还说自己是什么师范大学的
点赞 评论 收藏
分享
03-19 10:07
已编辑
广东药科大学 golang
Yki_:你倒是进一个面啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务