Skip to content

Commit c00e32e

Browse files
authored
0061_Rotate_List.java
1 parent ea13071 commit c00e32e

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

0061_Rotate_List.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
* }
10+
*/
11+
class Solution {
12+
public ListNode rotateRight(ListNode head, int k) {
13+
if (head == null || head.next == null || k == 0) {
14+
return head;
15+
}
16+
17+
// Find the length of the linked list
18+
int len = 1;
19+
ListNode tail = head;
20+
while (tail.next != null) {
21+
len++;
22+
tail = tail.next;
23+
}
24+
25+
// Make it a circular linked list
26+
tail.next = head;
27+
28+
// Find the new head and break the cycle
29+
k = k % len;
30+
int gap = len - k;
31+
ListNode newTail = head;
32+
33+
while (--gap > 0) {
34+
newTail = newTail.next;
35+
}
36+
37+
ListNode newHead = newTail.next;
38+
newTail.next = null;
39+
40+
return newHead;
41+
}
42+
}

0 commit comments

Comments
 (0)