Skip to main content

61. 旋转链表 [medium]

61. 旋转链表 [medium]

https://leetcode-cn.com/problems/rotate-list/

给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。

示例 1:

输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL

示例 2:

输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL
解释:
向右旋转 1 步: 2->0->1->NULL
向右旋转 2 步: 1->2->0->NULL
向右旋转 3 步: 0->1->2->NULL
向右旋转 4 步: 2->0->1->NULL

通过次数69,769 | 提交次数172,566

First Try

2020-07-06

要是真的跟着模拟一步步选择,写起来就头疼了,还好观察后发现有规律。

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

class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
# 要是真的一步步跟着旋转,那写起来就头疼了
if not head:
return head
# 先一波找出链表尾部,链表长度
node = head
n = 1
while node.next :
node = node.next
n += 1
tail = node

#判断是否需要循环
swift = k % n
if swift == 0:
return head

# 真是需要挪动的次数,其实旋转后两侧的排序依然保持不边
rank = n - swift
tail.next = head

node = head
c = 1
while c < rank:
node = node.next
c += 1
head = node.next
node.next = None
return head
  • 执行用时:20 ms, 在所有 Python 提交中击败了95.24%的用户
  • 内存消耗:12.7 MB, 在所有 Python 提交中击败了11.11%的用户