难度:中等
题目描述:
思路总结:这题比之前做的链表题内容都丰富。需要经常回顾。首先第一种思路是递归,虽然超时了,但是思路是正确的。通过返回链表尾连接父问题的头结点,然后不断求解子问题。(len-2)
第二种思路使用了翻转链表的思想,整体分为三步,找中点,翻转后半部分,连接成一个重排链表。其中找中点利用了快慢指针,翻转链表用的是pre,cur双指针,重排链表是一个需要更新前后三个结点next的问题,还涉及到了while循环结束条件、连接前后两部分链表等细节处理。
题解一:(递归)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
import functools
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head or not head.next or not head.next.next:return None
@functools.lru_cache(None)
def helper(h, ll):
if ll == 1:
h.next = None
return h
if h.next and ll == 2:
h.next.next = None
return h
tail = h
for i in range(1,ll):
tail = tail.next
hNext = h.next
h.next = tail
tail.next = helper(hNext, ll-2)
return h
h = head
listLen = 0
while h:
listLen += 1
h = h.next
return helper(head, listLen)
题解一结果:
超时
题解二:(翻转链表思想)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
import functools
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head or not head.next or not head.next.next:return None
#思路:借用翻转链表的思想,找到中点,分别翻转后半部分链表,拼接成一个链表后,交替拼接。
fast = head
mid = head
while fast.next and fast.next.next:
mid = mid.next
fast = fast.next.next
pre = None
cur = mid.next
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
mid.next = pre
h1 = head
h2 = pre
while h1 != mid:
mid.next = h2.next
h2.next = h1.next
h1.next = h2
h1 = h2.next
h2 = mid.next
题解二结果: