File tree 1 file changed +68
-0
lines changed
1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * 61. Rotate List
3
+ *
4
+ * Given a linked list, rotate the list to the right by k places, where k is non-negative.
5
+ *
6
+ * Example 1:
7
+ *
8
+ * Input: 1->2->3->4->5->NULL, k = 2
9
+ * Output: 4->5->1->2->3->NULL
10
+ * Explanation:
11
+ * rotate 1 steps to the right: 5->1->2->3->4->NULL
12
+ * rotate 2 steps to the right: 4->5->1->2->3->NULL
13
+ *
14
+ * Example 2:
15
+ *
16
+ * Input: 0->1->2->NULL, k = 4
17
+ * Output: 2->0->1->NULL
18
+ * Explanation:
19
+ * rotate 1 steps to the right: 2->0->1->NULL
20
+ * rotate 2 steps to the right: 1->2->0->NULL
21
+ * rotate 3 steps to the right: 0->1->2->NULL
22
+ * rotate 4 steps to the right: 2->0->1->NULL
23
+ */
24
+
25
+ /**
26
+ * Definition for singly-linked list.
27
+ * function ListNode(val) {
28
+ * this.val = val;
29
+ * this.next = null;
30
+ * }
31
+ */
32
+ /**
33
+ * @param {ListNode } head
34
+ * @param {number } k
35
+ * @return {ListNode }
36
+ */
37
+ var rotateRight = function ( head , k ) {
38
+ var count = 1 ;
39
+ var last = head ;
40
+ var now = head ;
41
+
42
+ if ( ! head || ! head . next ) return head ;
43
+
44
+ while ( last . next ) {
45
+ last = last . next ;
46
+ count ++ ;
47
+ }
48
+
49
+ k %= count ;
50
+
51
+ if ( k === 0 ) return head ;
52
+
53
+ while ( k < count - 1 ) {
54
+ now = now . next ;
55
+ k ++ ;
56
+ }
57
+
58
+ last . next = head ;
59
+ head = now . next ;
60
+ now . next = null ;
61
+
62
+ return head ;
63
+ } ;
64
+
65
+ // 1. 拿到长度 count 和最后一个 last
66
+ // 2. k %= count
67
+ // 3. 找到新的最后一个 newLast,last.next = head,head = newLast.next,newLast.next = null
68
+ // 4. return head
You can’t perform that action at this time.
0 commit comments