Java solution 2ms


  • 0
    G
    public class Solution {
        public ListNode rotateRight(ListNode head, int k) {
    		if (head == null || head.next == null || k == 0) return head;
    		int len = 0;
    		ListNode tail = head;
    		while(tail != null) {
    			tail = tail.next;
    			len++;
    		}				
    		int num = k > len ? k % len : k;
    		if (num == 0 || k == len) return head;
    		
    		int cnt = 0;
    		while (cnt < num) {
    			tail = head;
    			ListNode prev = head;
    			while (tail.next != null) {
    				prev = tail;
    				tail = tail.next;			
    			}
    			prev.next = null;
    			tail.next = head;			
    			head = tail;			
    			cnt++;
    		}
    		return head;        
        }
    }
    

  • 0
    N

    probably can change the last part as this. would be a little clearer. And thank you for this code, helped me a lot.

    for(int cnt = 0; cnt<(length-num); cnt++){
    tail.next = head;
    tail = tail.next;
    head = head.next;
    }
    tail.next = null;
    return head;


Log in to reply
 

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