leetcode-----61. 旋转链表

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if (!head) return head;
        int n = 0;
        ListNode* tail;
        for (auto p = head; p; p = p->next) {
            tail = p;
            n++;
        }   
        k %= n;
        if (!k) return head;

        auto p = head; 
        for (int i = 0; i < n - k - 1; ++i) p = p->next;
        tail->next = head;
        head = p->next;
        p->next = nullptr;
        return head;
    }
};
原文地址:https://www.cnblogs.com/clown9804/p/13262393.html