# 【Leetcode】61.旋转链表

```输入: 1->2->3->4->5->NULL, k = 2

```输入: 0->1->2->NULL, k = 4

# 题解

## python版本

```# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
"""
:type k: int
:rtype: ListNode
"""
# 链表的节点个数
count = 1
while cur.next:
count += 1
cur = cur.next
# 如果恰好走了一个环,就直接返回
k = k % count
if k == 0:
dummy = ListNode(-1)
prev = dummy
# 需要走count-k个,然后把链表切断
for _ in range(count - k):
prev = prev.next
# 重新组成新的链表
cur = prev.next

prev.next = None

## java版本

```public class Solution {
public ListNode rotateRight(ListNode head, int k) {
}

int count = 1;
while (cur.next != null) {
count++;
cur = cur.next;
}
k = k % count;
if (k == 0) {
}
ListNode dummy = new ListNode(-1);
ListNode prev = dummy;
for (int i = 0; i < count - k; i++) {
prev = prev.next;
}
cur = prev.next;
prev.next = null;
return cur;
}
}```

79 篇文章17 人订阅

0 条评论

## 相关文章

3315

1044

1653

2274

2622

1172

771

### Leetcode 239. Sliding Window Maximum

Given an array nums, there is a sliding window of size k which is moving from t...

2055

### 每周学点大数据 | No.43 相似连接的可扩展性

No.43期 相似连接的可扩展性 小可：那么具体是怎么做的呢？ Mr. 王：我们先来看看求单元函数值是如何在 MapReduce 上实现的吧。 ? 图中有三...

3547

692