Leetcode 61. Rotate List

文章作者:Tyan
博客:noahsnail.com  |  ****  |  简书

1. Description

Leetcode 61. Rotate List

2. Solution

/**
 * 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* pre = nullptr;
        ListNode* current = head;
        while(current) {
            n++;
            pre = current;
            current = current->next; 
        }
        pre->next = head;
        int target = n - k % n;
        current = head;
        while(target) {
            target--;
            pre = current;
            current = current->next;
        }
        pre->next = nullptr;
        return current;
    }
};

Reference

  1. https://leetcode.com/problems/rotate-list/description/