算法思路
- 首先确定链表的长度,然后使用k对这个长度取余数,这样避免循环计算
- 找到倒数第k个节点作为头结点
- 一直往后遍历到None,连接到首节点
- 将最后的节点置为None
其实有个更方便的办法:先将链表连接为循环链表(遍历链表长度的时候,就可以连接成循环链表)然后想办法从中间截断,不过时间复杂度是一样的
class Solution:
def listLength(self, head):
length = 0
p = head
while p:
length += 1
p = p.next
return length
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if head == None:
return None
k = k % (self.listLength(head))
if k == 0:
return head
p = head
for i in range(k):
p = p.next
newHead = head
while p:
p = p.next
newHead = newHead.next
p = newHead
while p.next:
p = p.next
p.next = head
p = head
while p.next != newHead:
p = p.next
p.next = None
return newHead