Skip to content

Commit 3c06bda

Browse files
solves rotate list
1 parent 001977e commit 3c06bda

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@
5858
| 57 | [Insert Interval](https://leetcode.com/problems/insert-interval) | [![Java](assets/java.png)](src/InsertInterval.java) | |
5959
| 58 | [Length of Last Word](https://leetcode.com/problems/length-of-last-word) | [![Java](assets/java.png)](src/LengthOfLastWord.java) [![Python](assets/python.png)](python/length_of_last_word.py) | |
6060
| 59 | [Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii) | [![Java](assets/java.png)](src/SpiralMatrixII.java) | |
61+
| 61 | [Rotate List](https://leetcode.com/problems/rotate-list) | [![Java](assets/java.png)](src/RotateList.java) | |
6162
| 66 | [Plus One](https://leetcode.com/problems/plus-one) | [![Java](assets/java.png)](src/PlusOne.java) [![Python](assets/python.png)](python/plus_one.py) | |
6263
| 67 | [Add Binary](https://leetcode.com/problems/add-binary) | [![Java](assets/java.png)](src/AddBinary.java) [![Python](assets/python.png)](python/add_binary.py) | |
6364
| 69 | [Sqrt(x)](https://leetcode.com/problems/sqrtx) | [![Java](assets/java.png)](src/Sqrtx.java) [![Python](assets/python.png)](python/sqrt.py) | |

src/RotateList.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// https://leetcode.com/problems/rotate-list
2+
// T: O(N)
3+
// S: O(1)
4+
5+
public class RotateList {
6+
public static class ListNode {
7+
int val;
8+
ListNode next;
9+
ListNode() {}
10+
ListNode(int val) { this.val = val; }
11+
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
12+
}
13+
14+
public ListNode rotateRight(ListNode head, int k) {
15+
final int length = getLength(head);
16+
if (length == 0) return head;
17+
final int rotations = k % length;
18+
if (rotations == 0) return head;
19+
final ListNode last = getLastNode(head);
20+
final ListNode cutoffNode = getCutoffNode(head, rotations, length);
21+
final ListNode newHead = cutoffNode.next;
22+
last.next = head;
23+
cutoffNode.next = null;
24+
return newHead;
25+
}
26+
27+
private int getLength(ListNode head) {
28+
int length = 0;
29+
ListNode current = head;
30+
while (current != null) {
31+
current = current.next;
32+
length++;
33+
}
34+
return length;
35+
}
36+
37+
private ListNode getLastNode(ListNode head) {
38+
ListNode current = head;
39+
while (current.next != null) {
40+
current = current.next;
41+
}
42+
return current;
43+
}
44+
45+
private ListNode getCutoffNode(ListNode head, int rotations, int length) {
46+
ListNode current = head;
47+
for (int i = 0 ; i < length - rotations - 1 ; i++) {
48+
current = current.next;
49+
}
50+
return current;
51+
}
52+
}

0 commit comments

Comments
 (0)