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

Have you met this question in a real interview?

Yes

Example

Given1->2->3->4->5and k =2, return4->5->1->2->3.

public class Solution {
    /**
     * @param head: the List
     * @param k: rotate to the right k places
     * @return: the list after rotation
     */
    public ListNode rotateRight(ListNode head, int k) {
        // write your code here
        if (head == null) {
            return head;
        }

        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;

        int size = 0;
        while (head != null && head.next != null) {
            head = head.next;
            size++;
        }

        head = dummy.next;

        for (int i = 1; i < size - k % size; i++) {
            head = head.next;
        }

        ListNode temp = head.next;
        head.next = null;

        ListNode newDummy = new ListNode(0);
        newDummy.next = temp;
        head = newDummy;

        while (head != null && head.next != null) {
            head = head.next;
        }

        head.next = dummy.next;
        return newDummy.next;


    }

}

results matching ""

    No results matching ""