Java simple and clean solution with some comments.


  • 0
    J
      public ListNode rotateRight(ListNode head, int k) {
        if (head == null || head.next == null || k == 0)
            return head;
        
        //find out the number of nodes in  the list.
    	ListNode cur = head;
    	int n = 0;
        while (cur != null) {
        	cur = cur.next;
          	n++;
        }
        
        //calculate the actually shifts it needs.
        k = k%n;
        
        if (k == 0) return head; //no shift is needed.
        
        //use fast and slow pointers to find out the k-the position from end and rotate.
        ListNode fast = head, slow = head, tail = null;
        while (fast != null) {
        	if (k-- < 0) {
        		slow = slow.next;
        	}
        	tail = fast;
        	fast = fast.next;
        }
        tail.next = head; //join the first part.
        head = slow.next; // record the new head.
        slow.next = null; // make the new tail.
        return head;
    }

Log in to reply
 

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