Someone please suggest how to write cleaner and more optimized version of this. This is 15ms code.


  • 0
    M

    '''
    /**

    • Definition for singly-linked list.
    • public class ListNode {
    • int val;
      
    • ListNode next;
      
    • ListNode(int x) { val = x; }
      
    • }
      */
      public class Solution {
      public ListNode rotateRight(ListNode head, int k) {
      if(head==null||head.next==null)
      return head;
      if(k==0)
      return head;
      ListNode front=head, back=head;
      int i=0;
      while(front!=null){
      i++;
      front=front.next;
      }
      int noOfRotations=k%i;
      if(noOfRotations==0)
      return head;
      i=0;
      front=head;
      while(i!=noOfRotations){
      front=front.next;
      if(front==null)
      front=head;
      i++;
      }
      while(front.next!=null)
      {
      front=front.next;
      back=back.next;
      }
      front.next=head;
      head=back.next;
      back.next=null;
      return head;
      }
      }
      '''

Log in to reply
 

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