R4-链表篇
三题都是类似的解。
链表的中间结点
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow=fast=head
while fast and fast.next:
slow=slow.next
fast=fast.next.next
return slow
反转链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
#以开始那两个结点为例说明
pre=None
cur=head
while cur:
nxt=cur.next
cur.next=pre
pre=cur
cur=nxt
return pre
重排链表
把前面两题写成函数,分别调用。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
#先找链表的中间结点,即[mid,mid.next,------]
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
#把中间结点反转
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
pre, cur = None, head
while cur:
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
return pre
#插入
def reorderList(self, head: Optional[ListNode]) -> None:
"""
Do not return anything, modify head in-place instead.
"""
mid = self.middleNode(head)
head2 = self.reverseList(mid)
#插入
while head2.next:
#分别保存两个链表的下一个结点
nxt=head.next
nxt2=head2.next
#开始调换
head.next=head2
head2.next=nxt
#下一个状态
head=nxt
head2=nxt2