File tree Expand file tree Collapse file tree 2 files changed +55
-8
lines changed Expand file tree Collapse file tree 2 files changed +55
-8
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ The basic idea is to link the tail of the list with the head, make it a cycle. Then count to the rotate point and cut it.
3
+ O(n) runtime, O(1) space.
4
+ */
5
+ public class Solution {
6
+ public ListNode RotateRight ( ListNode head , int k ) {
7
+ if ( head == null || head . next == null ) return head ;
8
+ // get length
9
+ int len = 1 ;
10
+ ListNode tail = head ;
11
+ while ( tail . next != null ) {
12
+ tail = tail . next ;
13
+ len ++ ;
14
+ }
15
+ // connect circle
16
+ tail . next = head ;
17
+ // find new head;
18
+ var n = len - k % len ;
19
+ while ( n > 0 ) {
20
+ tail = head ;
21
+ head = head . next ;
22
+ n -- ;
23
+ }
24
+ // cut before the new head
25
+ tail . next = null ;
26
+ return head ;
27
+ }
28
+ }
29
+
30
+ /*
31
+ Similar Questions
32
+ Rotate Array
33
+ Split Linked List in Parts
34
+ */
Original file line number Diff line number Diff line change @@ -6,17 +6,30 @@ namespace LeetcodeCShaprDotNetCore
6
6
{
7
7
public class Solution
8
8
{
9
- public bool IsPalindrome ( string s )
9
+ public ListNode RotateRight ( ListNode head , int k )
10
10
{
11
- int left = 0 , right = s . Length - 1 ;
12
- while ( left < right )
11
+ if ( head == null || head . next == null ) return head ;
12
+ // get length
13
+ int len = 1 ;
14
+ ListNode tail = head ;
15
+ while ( tail . next != null )
13
16
{
14
- while ( left < right && ! char . IsLetterOrDigit ( s [ left ] ) ) left ++ ;
15
- while ( left < right && ! char . IsLetterOrDigit ( s [ right ] ) ) right -- ;
16
- if ( char . ToLower ( s [ left ] ) != char . ToLower ( s [ right ] ) ) return false ;
17
- left ++ ; right -- ;
17
+ tail = tail . next ;
18
+ len ++ ;
18
19
}
19
- return true ;
20
+ // connect circle
21
+ tail . next = head ;
22
+ // find new head;
23
+ var n = len - k % len ;
24
+ while ( n > 0 )
25
+ {
26
+ tail = head ;
27
+ head = head . next ;
28
+ n -- ;
29
+ }
30
+ // cut before the new head
31
+ tail . next = null ;
32
+ return head ;
20
33
}
21
34
}
22
35
}
You can’t perform that action at this time.
0 commit comments