Leetcode练习,Python:链表类:第61题:旋转链表:给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。

题目:

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

思路:

将链表成环进行旋转,对于K,需要判断数目,使用超过了链表的长度。

程序:

# Definition for singly-linked list.

# class ListNode:

# def __init__(self, x):

# self.val = x

# self.next = None

class Solution:

def rotateRight(self, head: ListNode, k: int) -> ListNode:

if not head:

return None

length = 0

index = head

while index.next:

index = index.next

length += 1

index.next = head

length = length + 1

k = k % length

for i in range(length - k):

head = head.next

index = index.next

index.next = None

return head