61. 旋转链表
1.题目
2.我的解决方案
- 思路:形成单向循环链表
- 在length-k处断开
# 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: ListNode, k: int) -> ListNode:
def getLen(head):
cur = head
length = 0
while cur:
length += 1
cur = cur.next
return length
length = getLen(head) # 计算长度
if length == 0: # 空链表
return head
cur = head
while cur.next: # 判断下一个节点是否存在
cur = cur.next
cur.next = head # 形成单向循环链表
k %= length
count = 1
cur = head
while count < length - k:
cur = cur.next
count += 1 # (表示cur前+cur)为count个
head = cur.next
cur.next = None
return head
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( 1 ) O(1) O(1)