Share my java solution


  • 1
    X
    public class Solution {
        public ListNode rotateRight(ListNode head, int n) {
            
            if(head==null){
                return null;
            }         
            int length = 0;
            ListNode head2;
            head2 = head; 
            while(head2!=null){
                length++;
                head2 = head2.next;
            }            
            n = n%length;            
            if(n==0){
                return head;
            }
            
            ListNode point1 = new ListNode(0);
            ListNode point2 = new ListNode(0);            
            ListNode post2;
            
            point1.next = head;
            point2.next = head;
            for(int i=0; i<n; i++){
                    point1 = point1.next;
            }
            
            while(point1.next!=null){
                point1 = point1.next;
                point2 = point2.next;
            }
            
            post2 = point2.next;           
            point1.next = head;
            point2.next = null;
            return post2;
            
        }
    }

Log in to reply
 

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