力扣00061.旋转链表


题目描述

给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。

示例 1:

输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]

示例 2:

输入:head = [0,1,2], k = 4
输出:[2,0,1]

提示:

  • 链表中节点的数目在范围 [0, 500] 内
  • -100 <= Node.val <= 100
  • $0 <= k <= 2 * 10^9$

解决方法

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if (!head || k == 0) {
return head;
}
int length = 1;
ListNode *current = head;
while (current->next) {
length++;
current = current->next;
}
k = k % length;
if (k == 0) {
return head;
}
ListNode *fast = head;
ListNode *slow = head;
for (int i = 0; i < k; i++) {
fast = fast->next;
}
while (fast->next) {
fast = fast->next;
slow = slow->next;
}
ListNode *new_head = slow->next;
slow->next = NULL;
fast->next = head;
return new_head;
}
};

结果

执行用时 : 5 ms, 击败 53.76% 使用 C++ 的用户

内存消耗 : 14.91 MB, 击败 13.56% 使用 C++ 的用户


Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null || k == 0) {
return head;
}
int length = 1;
ListNode current = head;
while (current.next != null) {
length++;
current = current.next;
}
k = k % length;
if (k == 0) {
return head;
}
ListNode fast = head;
ListNode slow = head;
for (int i = 0; i < k; i++) {
fast = fast.next;
}
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
ListNode newHead = slow.next;
slow.next = null;
fast.next = head;
return newHead;
}
}

结果

执行用时 : 0 ms, 击败 100.00% 使用 Java 的用户

内存消耗 : 41.34 MB, 击败 52.48% 使用 Java 的用户


Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head or k == 0:
return head
length = 1
current = head
while current.next:
length += 1
current = current.next
k = k % length
if k == 0:
return head
fast = head
slow = head
for _ in range(k):
fast = fast.next
while fast.next:
fast = fast.next
slow = slow.next
new_head = slow.next
slow.next = None
fast.next = head
return new_head

结果

执行用时 : 23 ms, 击败 42.32% 使用 Python 的用户

内存消耗 : 11.53 MB, 击败 71.87% 使用 Python 的用户


Python3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
if not head or k == 0:
return head
length = 1
current = head
while current.next:
length += 1
current = current.next
k = k % length
if k == 0:
return head
fast = head
slow = head
for _ in range(k):
fast = fast.next
while fast.next:
fast = fast.next
slow = slow.next
new_head = slow.next
slow.next = None
fast.next = head
return new_head

结果

执行用时 : 46 ms, 击败 29.19% 使用 Python3 的用户

内存消耗 : 16.41 MB, 击败 57.60% 使用 Python3 的用户


C

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* rotateRight(struct ListNode* head, int k) {
if (!head || k == 0) {
return head;
}
int length = 1;
struct ListNode *current = head;
while (current->next) {
length++;
current = current->next;
}
k = k % length;
if (k == 0) {
return head;
}
struct ListNode *fast = head;
struct ListNode *slow = head;
for (int i = 0; i < k; i++) {
fast = fast->next;
}
while (fast->next) {
fast = fast->next;
slow = slow->next;
}
struct ListNode *newHead = slow->next;
slow->next = NULL;
fast->next = head;
return newHead;
}

结果

执行用时 : 2 ms, 击败 74.04% 使用 C 的用户

内存消耗 : 5.82 MB, 击败 91.17% 使用 C 的用户


C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode RotateRight(ListNode head, int k) {
if (head == null || k == 0) {
return head;
}
int length = 1;
ListNode current = head;
while (current.next != null) {
length++;
current = current.next;
}
k = k % length;
if (k == 0) {
return head;
}
ListNode fast = head;
ListNode slow = head;
for (int i = 0; i < k; i++) {
fast = fast.next;
}
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
ListNode newHead = slow.next;
slow.next = null;
fast.next = head;
return newHead;
}
}

结果

执行用时 : 64 ms, 击败 72.18% 使用 C# 的用户

内存消耗 : 41.42 MB, 击败 27.07% 使用 C# 的用户


JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
var rotateRight = function(head, k) {
if (!head || k === 0) {
return head;
}
let length = 1;
let current = head;
while (current.next) {
length++;
current = current.next;
}
k = k % length;
if (k === 0) {
return head;
}
let fast = head;
let slow = head;
for (let i = 0; i < k; i++) {
fast = fast.next;
}
while (fast.next) {
fast = fast.next;
slow = slow.next;
}
let newHead = slow.next;
slow.next = null;
fast.next = head;
return newHead;
};

结果

执行用时 : 64 ms, 击败 81.59% 使用 JavaScript 的用户

内存消耗 : 51.45 MB, 击败 13.45% 使用 JavaScript 的用户


TypeScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/

function rotateRight(head: ListNode | null, k: number): ListNode | null {
if (!head || k === 0) {
return head;
}
let length = 1;
let current = head;
while (current.next) {
length++;
current = current.next;
}
k = k % length;
if (k === 0) {
return head;
}
let fast: ListNode | null = head;
let slow: ListNode | null = head;
for (let i = 0; i < k; i++) {
if (fast) {
fast = fast.next;
}
}
while (fast && fast.next) {
fast = fast.next;
slow = slow?.next || null;
}
let newHead: ListNode | null = slow?.next || null;
if (slow) {
slow.next = null;
}
if (fast) {
fast.next = head;
}
return newHead;
}

结果

执行用时 : 68 ms, 击败 80.00% 使用 TypeScript 的用户

内存消耗 : 52.75 MB, 击败 5.56% 使用 TypeScript 的用户


PHP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Definition for a singly-linked list.
* class ListNode {
* public $val = 0;
* public $next = null;
* function __construct($val = 0, $next = null) {
* $this->val = $val;
* $this->next = $next;
* }
* }
*/
class Solution {

/**
* @param ListNode $head
* @param Integer $k
* @return ListNode
*/
function rotateRight($head, $k) {
if (!$head || $k === 0) {
return $head;
}
$length = 1;
$current = $head;
while ($current->next) {
$length++;
$current = $current->next;
}
$k = $k % $length;
if ($k === 0) {
return $head;
}
$fast = $head;
$slow = $head;
for ($i = 0; $i < $k; $i++) {
$fast = $fast->next;
}
while ($fast->next) {
$fast = $fast->next;
$slow = $slow->next;
}
$newHead = $slow->next;
$slow->next = null;
$fast->next = $head;
return $newHead;
}
}

结果

执行用时 : 12 ms, 击败 50.00% 使用 PHP 的用户

内存消耗 : 20.07 MB, 击败 10.00% 使用 PHP 的用户


Swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init() { self.val = 0; self.next = nil; }
* public init(_ val: Int) { self.val = val; self.next = nil; }
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
* }
*/
class Solution {
func rotateRight(_ head: ListNode?, _ k: Int) -> ListNode? {
guard let head = head, k > 0 else {
return head
}
var length = 1
var current = head
while current.next != nil {
length += 1
current = current.next!
}
let rotateSteps = k % length
if rotateSteps == 0 {
return head
}
var fast: ListNode? = head
var slow: ListNode? = head
for _ in 0..<rotateSteps {
fast = fast?.next
}
while fast?.next != nil {
fast = fast?.next
slow = slow?.next
}
let newHead = slow?.next
slow?.next = nil
fast?.next = head
return newHead
}
}

结果

执行用时 : 9 ms, 击败 70.89% 使用 Swift 的用户

内存消耗 : 15.43 MB, 击败 11.39% 使用 Swift 的用户


Kotlin

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class Solution {
fun rotateRight(head: ListNode?, k: Int): ListNode? {
if (head == null || k == 0) {
return head
}
var length = 1
var current = head
while (current?.next != null) {
length++
current = current.next
}
val rotateSteps = k % length
if (rotateSteps == 0) {
return head
}
var fast: ListNode? = head
var slow: ListNode? = head
repeat(rotateSteps) {
fast = fast?.next
}
while (fast?.next != null) {
fast = fast?.next
slow = slow?.next
}
val newHead = slow?.next
slow?.next = null
fast?.next = head
return newHead
}
}

结果

执行用时 : 167 ms, 击败 90.70% 使用 Kotlin 的用户

内存消耗 : 35.81 MB, 击败 30.23% 使用 Kotlin 的用户


Dart

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode? next;
* ListNode([this.val = 0, this.next]);
* }
*/
class Solution {
ListNode? rotateRight(ListNode? head, int k) {
if (head == null || k == 0) {
return head;
}
int length = 1;
ListNode? current = head;
while (current?.next != null) {
length++;
current = current?.next;
}
k = k % length;
if (k == 0) {
return head;
}
ListNode? fast = head;
ListNode? slow = head;
for (int i = 0; i < k; i++) {
fast = fast?.next;
}
while (fast?.next != null) {
fast = fast?.next;
slow = slow?.next;
}
ListNode? newHead = slow?.next;
slow?.next = null;
fast?.next = head;
return newHead;
}
}

结果

执行用时 : 292 ms, 击败 100.00% 使用 Dart 的用户

内存消耗 : 144.09 MB, 击败 100.00% 使用 Dart 的用户


Go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func rotateRight(head *ListNode, k int) *ListNode {
if head == nil || k == 0 {
return head
}
length := 1
current := head
for current.Next != nil {
length++
current = current.Next
}
k = k % length
if k == 0 {
return head
}
fast, slow := head, head
for i := 0; i < k; i++ {
fast = fast.Next
}
for fast.Next != nil {
fast = fast.Next
slow = slow.Next
}
newHead := slow.Next
slow.Next = nil
fast.Next = head
return newHead
}

结果

执行用时 : 0 ms, 击败 100.00% 使用 Go 的用户

内存消耗 : 2.36 MB, 击败 34.33% 使用 Go 的用户


Ruby

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val = 0, _next = nil)
# @val = val
# @next = _next
# end
# end
# @param {ListNode} head
# @param {Integer} k
# @return {ListNode}
def rotate_right(head, k)
return head if head.nil? || k.zero?
length = 1
current = head
while current.next
length += 1
current = current.next
end
k = k % length
return head if k.zero?
fast = head
slow = head
k.times { fast = fast.next }
while fast.next
fast = fast.next
slow = slow.next
end
new_head = slow.next
slow.next = nil
fast.next = head
new_head
end

结果

执行用时 : 64 ms, 击败 25.00% 使用 Ruby 的用户

内存消耗 : 206.50 MB, 击败 50.00% 使用 Ruby 的用户


Scala

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Definition for singly-linked list.
* class ListNode(_x: Int = 0, _next: ListNode = null) {
* var next: ListNode = _next
* var x: Int = _x
* }
*/
object Solution {
def rotateRight(head: ListNode, k: Int): ListNode = {
if (head == null || k == 0) {
return head
}
var length = 1
var current = head
while (current.next != null) {
length += 1
current = current.next
}
val rotateSteps = k % length
if (rotateSteps == 0) {
return head
}
var fast: ListNode = head
var slow: ListNode = head
for (_ <- 0 until rotateSteps) {
fast = fast.next
}
while (fast.next != null) {
fast = fast.next
slow = slow.next
}
val newHead: ListNode = slow.next
slow.next = null
fast.next = head
newHead
}
}

结果

执行用时 : 513 ms, 击败 50.00% 使用 Scala 的用户

内存消耗 : 56.80 MB, 击败 100.00% 使用 Scala 的用户


Rust

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
// pub val: i32,
// pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
// #[inline]
// fn new(val: i32) -> Self {
// ListNode {
// next: None,
// val
// }
// }
// }
impl Solution {
pub fn rotate_right(mut head: Option<Box<ListNode>>, k: i32) -> Option<Box<ListNode>> {
let mut len = 0;
let mut p = &head;
while let Some(node) = p {
len += 1;
p = &node.next;
}
if len <= 1 {
return head;
}
let k = k % len;
if k == 0 {
return head;
}
let mut p = Self::get_last_nth(&mut head, k);
let mut q = &mut p;
while (*q).is_some() && q.as_ref().unwrap().next.is_some() {
q = &mut q.as_mut().unwrap().next;
}
q.as_mut().unwrap().next = head;
p
}
fn get_last_nth(head: &mut Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> {
unsafe {
let mut slow = head as *mut Option<Box<ListNode>>;
let mut fast = head as *mut Option<Box<ListNode>>;
for _ in 0..n {
fast = &mut (*fast).as_mut().unwrap().next;
}
while (*fast).is_some() {
slow = &mut (*slow).as_mut().unwrap().next;
fast = &mut (*fast).as_mut().unwrap().next;
}
(*slow).take()
}
}
}

结果

执行用时 : 1 ms, 击败 24.14% 使用 Rust 的用户

内存消耗 : 2.13 MB, 击败 31.03% 使用 Rust 的用户


Racket

暂时未解决

1

结果

执行用时 : ms, 击败 % 使用 Racket 的用户

内存消耗 : MB, 击败 % 使用 Racket 的用户


Erlang

暂时未解决

1

结果

执行用时 : ms, 击败 % 使用 Erlang 的用户

内存消耗 : MB, 击败 % 使用 Erlang 的用户


Elixir

暂时未解决

1

结果

执行用时 : ms, 击败 % 使用 Elixir 的用户

内存消耗 : MB, 击败 % 使用 Elixir 的用户