61 Rotate List

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.

Solution)

First, find the length (n) of the given list.

Second, find the (n-k) from the head.

Finally, update new head.

/**
 * 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 || head.next==null || k==0) return head;
        ListNode dummy=new ListNode(0);
        ListNode fast=dummy,slow=dummy;
        dummy.next=head;
        int n=0; // size of the given list
        for (;fast.next!=null;n++)
            fast=fast.next;
        for (int j =n-k%n;j>0;j--)
            slow=slow.next;

        fast.next=dummy.next;
        dummy.next=slow.next;
        slow.next=null;
        return dummy.next;
    }
}

results matching ""

    No results matching ""