题目链接:https://leetcode.com/problems/rotate-list/
自己的思路
代码
# 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 or not head.next: return head
pre,cur,cnt=head,head.next,2
#遍历链表直至链表尾部,同时进行节点的计数
while cur.next:
cur,pre,cnt=cur.next,pre.next,cnt+1
#将链表尾部指向头部,形成环形链表,同时求k模节点数的值——非常重要
cur.next,move_step=head,k%(cnt)
#然后进行逆向需要移动的个数
for _ in range(abs(cnt-move_step+1)):
cur,pre=cur.next,pre.next
pre.next=None
return cur
思路详解
最后将pre指向None,断开环形链表即可。
注意点
- 求模部分很关键,时间复杂度可以大大的缩小
- 移动指针的时候,需要逆向思维