My Java Solution


  • 0
    G
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode rotateRight(ListNode head, int k) {
            if (head == null){
                return head;
            }
            ListNode p1, p2;
            p1 = head;
            p2 = head;
            //calculate length
            int l = 1;
            while(p2.next != null){
                l++;
                p2 = p2.next;
            }
            p2 = head;
            k = k % l;
            while(k > 0){
                k--;
                p2 = p2.next;
            }
            while(p2.next != null){
                p1 = p1.next;
                p2 = p2.next;
            }
            if(p1.next != null){//rearrange list
                p2.next = head;
                head = p1.next;
                p1.next = null;
            } 
            return head;
        }
    }

Log in to reply
 

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