Skip to content

Commit 64d6ce4

Browse files
committed
add Rotate List
1 parent 73ffaf9 commit 64d6ce4

File tree

2 files changed

+55
-8
lines changed

2 files changed

+55
-8
lines changed

CodeClearWar/61. Rotate List.cs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
*/

LeetcodeCShaprDotNetCore/Solution.cs

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,30 @@ namespace LeetcodeCShaprDotNetCore
66
{
77
public class Solution
88
{
9-
public bool IsPalindrome(string s)
9+
public ListNode RotateRight(ListNode head, int k)
1010
{
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)
1316
{
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++;
1819
}
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;
2033
}
2134
}
2235
}

0 commit comments

Comments
 (0)