Share my AC java solution, using two pointers


  • 0
    I
        public class Solution {
            public ListNode rotateRight(ListNode head, int n) {
    			if (head == null) {
    				return null;
    			} else if (n == 0) {
    				return head;
    			}
    			ListNode slow = head, fast = head, result = null;
    			int length = 0, pos = 0;
    			while (pos++ < n && fast != null) {
    				fast = fast.next;
    				length++;
    			}
    			if (fast == null) {
    				n %= length;
    				if (n == 0)
    					return head;
    				fast = head;
    				pos = 0;
    				while (pos++ < n && fast != null) {
    					fast = fast.next;
    				}
    			}
    			while (fast.next != null) {
    				fast = fast.next;
    				slow = slow.next;
    			}
    			result = slow.next;
    			slow.next = null;
    			fast.next = head;
    			return result;
            }
       }

Log in to reply
 

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