1.题目

【LeetCode】61.旋转链表_死循环

2. 分析

分割然后链接即可。

3. 代码

# 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 :
return head
length = 0
s = head
# 求出链表长度
while(s):
s = s.next
length+=1
k %= length
if k == 0:
return head
s = head
split_head = head # 分割后的链表头部
cnt = 0
pre = None
while(cnt < length - k):
pre = split_head
split_head = split_head.next
cnt += 1
pre.next = None # 这一步比较重要,否则后面会造成死循环
tmp = split_head
while(split_head):
pre = split_head
split_head = split_head.next
pre.next = s
return