61.Rotate List

get the total length

k = k % length, avoid cycle

split list to fpart and lpart

move to last element of fpart and assign next as lpart

https://leetcode.com/problems/rotate-list/discuss/22715/Share-my-java-solution-with-explanation

/**
 * 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)
            return head;
        ListNode fast = head;
        ListNode slow = head;
        int n = 1;

        while(fast.next != null){
            n++;
            fast = fast.next;
        }
        for(int i = n - k % n; i > 1; i--){
            slow = slow.next;
        }
        fast.next = head;
        head = slow.next;
        slow.next = null;
        return head;
    }
}

results matching ""

    No results matching ""