2 java solution


  • 0
    Q

    1.use two pointer p and q,q go k steps,p and q go until q at the end of the list.so we find the node where to cut.

    public ListNode rotateRight(ListNode head, int k) {
        if(k==0||head==null) return head;
        ListNode p=head,q=head;
        int step=0;
        while(step<k&&q!=null){
            q=q.next;
            step++;
        }
        if(q==null){
            return rotateRight(head, k%step);
        }
        else{
            while(q.next!=null){
                p=p.next;
                q=q.next;
            }
            q.next=head;
            head=p.next;
            p.next=null;
        }
        return head;
    }
    

    2.obtain the length of list, compute which node to cut

    public ListNode rotateRight(ListNode head, int k) {
        if(k==0||head==null||head.next==null) return head;
        ListNode p=head,q=head;
        int i=1;
        while(p.next!=null){
            i++;
            p=p.next;
        }
    
        for(int j=1,f=i-k%i;j<f;j++){
            q=q.next;
        }
        p.next=head;
        head=q.next;
        q.next=null;
        return head;
    }

Log in to reply
 

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