leetcode 61-70

61. 旋转链表

分析

leetcode 61-70
注意 k >= n, k %= n

code

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if (!head) return NULL;
        auto dummy = new ListNode(-1);
        dummy->next = head;
        int n = 0;
        auto b = dummy;
        for (auto p = head; p; p = p->next) {
            b = p;
            n ++;
        }
        if (k >= n) k %= n;
        if (k == 0) return head;
        
        k = n - k;
        auto p = dummy;
        for (int i = 0; i < k; i ++ ) p = p->next;
        auto a = p->next; // 4
        p->next = NULL;
        b->next = dummy->next;
        dummy->next = a;
        return dummy->next;
    }
};
上一篇:❤️19❤️带新手一起刷力扣 (LeetCode)❤️代码有详细的注释❤️反思总结❤️19. 删除链表的倒数第 N 个结点


下一篇:Leetcode 19.删除链表的倒数第N个节点