bozhilov

Rotate List O(n)

Mar 13th, 2022 (edited)
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.58 KB | None | 0 0
  1. class Solution {
  2.    
  3.    
  4.     public ListNode rotateRight(ListNode head, int k) {
  5.            if(head == null || k == 0 || head.next == null)
  6.             return head;
  7.        
  8.         ListNode curr = head;
  9.         int length = 1;
  10.         while(curr.next != null) {
  11.             length++;
  12.             curr = curr.next;
  13.         }
  14.         curr.next = head;
  15.         if(k % length!=0){
  16.         for( int  i = 0; i < length - (k%length); i++) {
  17.             curr = curr.next;
  18.         }}
  19.             head = curr.next;
  20.             curr.next = null;
  21.             return head;
  22.     }
  23. }
Add Comment
Please, Sign In to add comment