@@ -54,13 +54,11 @@ rotate 4 steps to the right: <code>2->0->1->NULL</code></pre>
5454# self.next = next
5555class Solution :
5656 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 :
5858 return head
59- n = 0
60- cur = head
59+ n, cur = 0 , head
6160 while cur:
62- n += 1
63- cur = cur.next
61+ n, cur = n + 1 , cur.next
6462 k %= n
6563 if k == 0 :
6664 return head
@@ -90,21 +88,21 @@ class Solution:
9088 */
9189class Solution {
9290 public ListNode rotateRight (ListNode head , int k ) {
93- if (head == null || head. next == null ) {
91+ if (k == 0 || head == null || head. next == null ) {
9492 return head;
9593 }
96- int n = 0 ;
9794 ListNode cur = head;
95+ int n = 0 ;
9896 while (cur != null ) {
99- ++ n;
10097 cur = cur. next;
98+ ++ n;
10199 }
102100 k %= n;
103101 if (k == 0 ) {
104102 return head;
105103 }
106104 ListNode p = head, q = head;
107- for ( int i = 0 ; i < k; ++ i ) {
105+ while (k -- > 0 ) {
108106 q = q. next;
109107 }
110108 while (q. next != null ) {
@@ -119,6 +117,57 @@ class Solution {
119117}
120118```
121119
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+
122171### ** ...**
123172
124173```
0 commit comments