File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments