File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Given a list, rotate the list to the right by k places, where k is
3
+ * non-negative.
4
+ *
5
+ * For example:
6
+ *
7
+ * Given 1->2->3->4->5->NULL and k = 2, return 4->5->1->2->3->NULL.
8
+ *
9
+ */
10
+
11
+ public class RotateList {
12
+ public ListNode rotateRight (ListNode head , int n ) {
13
+ if (head == null )
14
+ return head ;
15
+ int length = 1 ;
16
+ ListNode last = head ;
17
+ while (last .next != null ) {
18
+ last = last .next ;
19
+ length ++;
20
+ }
21
+ n = n % length ;
22
+ if (n == 0 )
23
+ return head ;
24
+ int steps = length - n ;
25
+ ListNode start = new ListNode (0 );
26
+ start .next = head ;
27
+ while (steps > 0 ) {
28
+ start = start .next ;
29
+ steps --;
30
+ }
31
+ ListNode ret = start .next ;
32
+ start .next = null ;
33
+ last .next = head ;
34
+ return ret ;
35
+ }
36
+ }
You can’t perform that action at this time.
0 commit comments