Very easy to understand O(n) solution. Modular Code.


  • 0
    K

    I am first finding the length of the list, modding the length by k (since k could be greater than the list size) and then nulling that nodes next pointer, while also connecting the last node to the first.

    public class Solution {
        public ListNode rotateRight(ListNode head, int k) {
            if(head == null){
                return null;
            }
            int len = getlen(head);
            ListNode last = getNode(head,-1);
            ListNode nullify = getNode(head, len-k%len-1);
            last.next = head;
            last = nullify.next; // Make the list circular so that pointer does not go to null
            nullify.next = null;
            return last;
            
        }
        
        public int getlen(ListNode head){ // Simple function to return length of list
            int total = 0;
            while(head != null){
                total++;
                head = head.next;
            }
            return total;
        }
        public ListNode getNode(ListNode head, int i){ // Simple function to get node at index i
            if(i==-1){
                while(head.next != null){
                    head = head.next;
                }
                return head;
            }
            while(i>0){
                i--;
                head = head.next;
            }
            return head;
        }
    }
    

Log in to reply
 

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