@@ -54,13 +54,11 @@ rotate 4 steps to the right: <code>2->0->1->NULL</code></pre>
54
54
# self.next = next
55
55
class Solution :
56
56
def rotateRight (self , head : ListNode, k : int ) -> ListNode:
57
- if head is None or head.next is None or k == 0 :
57
+ if k == 0 or head is None or head.next is None :
58
58
return head
59
- n = 0
60
- cur = head
59
+ n, cur = 0 , head
61
60
while cur:
62
- n += 1
63
- cur = cur.next
61
+ n, cur = n + 1 , cur.next
64
62
k %= n
65
63
if k == 0 :
66
64
return head
@@ -90,21 +88,21 @@ class Solution:
90
88
*/
91
89
class Solution {
92
90
public ListNode rotateRight (ListNode head , int k ) {
93
- if (head == null || head. next == null ) {
91
+ if (k == 0 || head == null || head. next == null ) {
94
92
return head;
95
93
}
96
- int n = 0 ;
97
94
ListNode cur = head;
95
+ int n = 0 ;
98
96
while (cur != null ) {
99
- ++ n;
100
97
cur = cur. next;
98
+ ++ n;
101
99
}
102
100
k %= n;
103
101
if (k == 0 ) {
104
102
return head;
105
103
}
106
104
ListNode p = head, q = head;
107
- for ( int i = 0 ; i < k; ++ i ) {
105
+ while (k -- > 0 ) {
108
106
q = q. next;
109
107
}
110
108
while (q. next != null ) {
@@ -119,6 +117,57 @@ class Solution {
119
117
}
120
118
```
121
119
120
+ ### ** C#**
121
+
122
+ ``` cs
123
+ /**
124
+ * Definition for singly-linked list.
125
+ * public class ListNode {
126
+ * public int val;
127
+ * public ListNode next;
128
+ * public ListNode(int val=0, ListNode next=null) {
129
+ * this.val = val;
130
+ * this.next = next;
131
+ * }
132
+ * }
133
+ */
134
+ public class Solution {
135
+ public ListNode RotateRight (ListNode head , int k ) {
136
+ if (k == 0 || head == null || head .next == null )
137
+ {
138
+ return head ;
139
+ }
140
+ ListNode cur = head ;
141
+ var n = 0 ;
142
+ while (cur != null )
143
+ {
144
+ cur = cur .next ;
145
+ ++ n ;
146
+ }
147
+ k %= n ;
148
+ if (k == 0 )
149
+ {
150
+ return head ;
151
+ }
152
+ ListNode p = head , q = head ;
153
+ while (k -- > 0 )
154
+ {
155
+ q = q .next ;
156
+ }
157
+ while (q .next != null )
158
+ {
159
+ p = p .next ;
160
+ q = q .next ;
161
+ }
162
+ ListNode start = p .next ;
163
+ p .next = null ;
164
+ q .next = head ;
165
+ return start ;
166
+
167
+ }
168
+ }
169
+ ```
170
+
122
171
### ** ...**
123
172
124
173
```
0 commit comments