Skip to content

Commit 7cef520

Browse files
authored
Merge pull request neetcode-gh#2230 from crazysamurai/add-problem
Create: 0061-rotate-list.java
2 parents 13832b0 + 2f99027 commit 7cef520

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

java/0061-rotate-list.java

+31
Original file line numberDiff line numberDiff line change
@@ -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+
temp = temp.next;
24+
k--;
25+
}
26+
head = temp.next;
27+
temp.next = null;
28+
29+
return head;
30+
}
31+
}

0 commit comments

Comments
 (0)