Java Solution with detailed explanatin


  • 1

    1 Calculate length of node list. If k%length(head)=0 return head.
    2 Use 2 pointer: fast and slow. Move fast k steps ahead slow.
    3 Move 2 pointer at the same pace until fast.next==null.
    4 Find new head slow.next. Assign null to slow.next to avoid circle.
    5 Concatenate first half to the end of second half.
    6 Return new head.

    public class Solution {
        public ListNode rotateRight(ListNode head, int k) {
            if(head==null||head.next==null)
                return head;
            k=k%length(head);
            if(k==0)
                return head;
            ListNode fast = head;
            ListNode slow = head;
            while(k-->0)
                fast=fast.next;
                
            while(fast.next!=null){
                fast=fast.next;
                slow=slow.next;
            }
            ListNode newHead=slow.next;
            slow.next=null;
            ListNode cur=newHead;
            while(cur.next!=null)
                cur=cur.next;
            cur.next=head;
            return newHead;
        }
        
        public int length(ListNode head){
            int res=0;
            while(head!=null){
                res++;
                head=head.next;
            }
            return res;
        }
    }

Log in to reply
 

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