Java solution, in most cases just go one traverse

  • 0
    public class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head==null||k==0) return head;
        ListNode fast = head;
        ListNode slow = head;
        int step;
        for(step=0;fast!=null&&step++<k;;//be careful that k is probably larger than the length of this list
        if(fast==null){//if the length of list is smaller than k
            k %= step;
            if(k==0) return head;
            for(step=0,fast=head;step++<k;;//fast pointer go first k steps
        for(;!=null;fast =,slow =;//slow pointer go to the forehead of the new head node
        ListNode nHead =; = null; = head;
        return nHead;


Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.