We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
2 parents 13832b0 + 2f99027 commit 7cef520Copy full SHA for 7cef520
java/0061-rotate-list.java
@@ -0,0 +1,31 @@
1
+//TC: O(n) + O(n- (n % k)) ~ O(n)
2
+//SC: O(1)
3
+
4
+class Solution {
5
+ public ListNode rotateRight(ListNode head, int k) {
6
+ if (head == null || head.next == null || k == 0)
7
+ return head;
8
9
+ int l = 1; // length of list
10
+ ListNode temp = head;
11
12
+ // calculate the list's length
13
+ while (temp.next != null) {
14
+ l++;
15
+ temp = temp.next;
16
+ }
17
18
+ temp.next = head; // make the list cyclic
19
+ k = k % l; // handles the case where k>l
20
+ k = l - k;
21
22
+ while (k > 0) {
23
24
+ k--;
25
26
+ head = temp.next;
27
+ temp.next = null;
28
29
30
31
+}
0 commit comments