思路:双指针。以图中例子,k= 2时,其实是把4后的链表放到前边,类似前面找到倒数第n个数
# 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
slow = fast = dummy = ListNode(-1)
dummy.next = head
count = 0
cur = head
while cur:
count += 1
cur = cur.next
if k >= count:
k = k % count
if k > 0:
for _ in range(k):
fast = fast.next
while fast.next:
fast = fast.next
slow = slow.next
dummy.next = slow.next
fast.next = head
slow.next = None
return dummy.next
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
# 初始化slow = head, fast = head.next,此后fast一次走两步,slow一次走一步,直到,fast下一步或下两步为None
# 经过上面的步骤,slow刚好是中间那个数(链表为奇数时如7,slow为3,链表为偶数时如8,slow为4)
# 为什么上述步骤后,slow为中间数。设链表长度为n,则fast会走 (n-1) // 2步,同时,slow也走同样的步数。
# 以n = 8为例,fast从第二数走 7//2=3大步,每大步为两小步,fast走到8,slow从1开始走3小步后到4
# 划分左右两边,以slow为分界线,左边包含slow,右边从slow.next开始,为了使右边包含slow,上述循环后令slow = slow.next
# 反转右边的链表
# 将左右两边两两相连
if not head or not head.next:
return
slow = head
fast = head.next
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
slow = slow.next # 使slow表示为右边
if fast.next:
fast = fast.next
# 反转右边的链表
pre = ListNode(-1)
pre.next = slow
cur = slow
nex = cur.next
while nex:
cur.next = nex.next
nex.next = pre.next
pre.next = nex
nex = cur.next
# 反转链表后fast变为右边链表的第一个
# 将左右两边连接起来,注意此时左边仍为整个链表
trav = head
while fast.next:
temp1 = trav.next
temp2 = fast.next
trav.next = fast
fast.next = temp1
fast = temp2
trav = temp1