Tuesday, May 30, 2017

61. Rotate List

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.



Solution:

If we know the length of the linked list, we know the new head after rotate is k % length - k.

Therefore, we go through the linked list and count the length.

After reaching the end, we connect the tail to the head.

From the tail, we go k % length - k steps and set the new head.

Also we need to set the tail node points to null.



Code:


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null) {
            return head;
        }
        ListNode curr = head;
        int len = 1;
        while (curr.next != null) {
            len++;
            curr = curr.next;
        }
        curr.next = head;
        k %= len;
        for (int i = 0; i < len - k; i++) {
            curr = curr.next;
        }
        head = curr.next;
        curr.next = null;
        return head;
        
    }
}