138. 复制带随机指针的链表
思路:芜湖!!!这是我第一次思路完全正确,并且代码八九不离十!!!并且还是中等题,开心!找中间节点+反转后半段+拼接
注意:循环条件还是把握不准,什么时候用 while cur,while cur.next,while cur.next.next
我的代码刚开始会超时,但是我还是不明白为什么,和官方差不多呀,只是因为它把每一步包装成函数了
代码:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
def reverse(slow):
prev=None
cur=slow.next
slow.next=None
while cur:
next=cur.next
cur.next=prev
prev=cur
cur=next
return prev
#找到最中间的节点,无需注意奇偶,利用快慢指针
slow=head
fast=head
while fast.next and fast.next.next:
slow=slow.next
fast=fast.next.next
#反转后半段链表
newHead=reverse(slow)
print(newHead)
# 两个链表拼接
curl=head
curr=newHead
while curr and curl:
nextl=curl.next
nextr=curr.next
curl.next=curr
curr.next=nextl
curl=nextl
curr=nextr
return head
#官方实现
class Solution:
def reorderList(self, head: ListNode) -> None:
if not head:
return
mid = self.middleNode(head)
l1 = head
l2 = mid.next
mid.next = None
l2 = self.reverseList(l2)
self.mergeList(l1, l2)
def middleNode(self, head: ListNode) -> ListNode:
slow = fast = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
return slow
def reverseList(self, head: ListNode) -> ListNode:
prev = None
curr = head
while curr:
nextTemp = curr.next
curr.next = prev
prev = curr
curr = nextTemp
return prev
def mergeList(self, l1: ListNode, l2: ListNode):
while l1 and l2:
l1_tmp = l1.next
l2_tmp = l2.next
l1.next = l2
l1 = l1_tmp
l2.next = l1
l2 = l2_tmp