Java solution O(n)


  • 0
    A
    public static ListNode rotateRight(ListNode head, int k) {
    		ListNode l = head;
    		int s = 0;
    		if (head == null)
    			return null;
    		while (l != null) {
    			s++;
    			l = l.next;
    		}
    		k = k % s;
    
    		if (k == s || k == 0)
    			return head;
    
    		l = head;
    		s--;
    		while (s != k) {
    			s--;
    			l = l.next;
    		}
    		ListNode n = l.next;
    		while (n.next != null) {
    			n = n.next;
    		}
    		n.next = head;
    		head = l.next;
    		l.next = null;
    		return head;
    
    	}
    

Log in to reply
 

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