Question

link

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

Stats

Frequency 2
Difficulty 3
Adjusted Difficulty 3
Time to use --------

Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)

Solution

This is a very basic question, but not very easy.

The implementation is a lot of node operations. The rest of things is straight-forward.

Read this blog for more.

My code

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode rotateRight(ListNode head, int n) {
        if (head == null) {
            return null;
        }
        ListNode p = head;
        for (int i = 0; i < n; i++) {
            if (p.next != null) {
                p = p.next;
            } else {
                p = head;
            }
        }
        ListNode q = head;
        while (p.next != null) {
            p = p.next;
            q = q.next;
        }
        if (q.next == null) {
            return head;
        }
        ListNode newHead = q.next;
        q.next = null;
        p.next = head;
        return newHead;
    }
}