Java solution, in most cases just go one traverse


  • 0
    W
    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;fast=fast.next);//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=fast.next);//fast pointer go first k steps
        }
        
        for(;fast.next!=null;fast = fast.next,slow = slow.next);//slow pointer go to the forehead of the new head node
        
        ListNode nHead = slow.next;
        slow.next = null;
        fast.next = head;
        return nHead;
    }
    

    }


Log in to reply
 

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