Skip to content

Commit

Permalink
0061
Browse files Browse the repository at this point in the history
  • Loading branch information
crazysamurai committed Feb 11, 2023
1 parent 3c00e2a commit 2f99027
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions java/0061-rotate-list.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
//TC: O(n) + O(n- (n % k)) ~ O(n)
//SC: O(1)

class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null || head.next == null || k == 0)
return head;

int l = 1; // length of list
ListNode temp = head;

// calculate the list's length
while (temp.next != null) {
l++;
temp = temp.next;
}

temp.next = head; // make the list cyclic
k = k % l; // handles the case where k>l
k = l - k;

while (k > 0) {
temp = temp.next;
k--;
}
head = temp.next;
temp.next = null;

return head;
}
}

0 comments on commit 2f99027

Please sign in to comment.