61. 旋转链表
->每个节点都要移动,因此想到连接到一起
1.找尾节点,形成环形链表
2.尾节点移动length-k步(又移k步==左移length-k步)
3.找到头节点,断开头尾连接
-<代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
demo1:
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
if not head or not head.next:
return head # 特例判断
tail = head # tail指向head
while tail.next:
length+=1
tail = tail.next #记录链表长度
tail.next=head #头尾相连
k %=length # 确定移动后的位置移动
for _ in range(length-k):
tail = tail.next
head = tail.next
tail.next = None #断开链表
return head
demo2:
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
# 若链表为空,返回head
if not head:
return head
# 获取链表的长度
n = 0
cur = head
while cur:
n += 1
cur = cur.next
# 若k的长度大于n,将k对n求余
k = k % n
# 若k==0表示循环了一整遍,直接返回head
if k == 0:
return head
# 创建快慢指针
slow = fast = head
# fast指针先走k步
while k:
fast = fast.next
k -= 1
# 让fast指针走到队尾
while fast.next:
fast = fast.next
slow = slow.next
# 此时show.next为新的链表头
new_head = slow.next
# 断开slow.next
slow.next = None
# 链表首位相接
fast.next = head
# 返回新的链表头
return new_head