61 Rotate List

1. Question

Given a list, rotate the list to the right bykplaces, wherekis non-negative.

Example:

Given 1->2->3->4->5->NULL and k= 2,

return 4->5->1->2->3->NULL.

2. Implementation

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || k == 0) {
            return head;
        }

        int len = 1;
        ListNode curNode = head;

        while (curNode.next != null) {
            curNode = curNode.next;
            ++len;
        }

        k %= len;
        curNode.next = head;

        for (int i = 0; i < len - k; i++) {
            curNode = curNode.next;
        }

        head = curNode.next;
        curNode.next = null;
        return head;
    }
}

3. Time & Space Complexity

时间复杂度O(n), 空间复杂度O(1)

Last updated