ZhongKuo0228 / study

0 stars 0 forks source link

2095. Delete the Middle Node of a Linked List #87

Open fockspaces opened 12 months ago

fockspaces commented 12 months ago
  1. 快慢指針,最後慢指針會停在中點
  2. prev 用來記錄慢指針前一個位置
  3. 將 prev 跳過中點,直接指下一位
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head.next:
            return None
        slow = fast = head
        prev = None
        while fast and fast.next:
            prev = slow
            slow = slow.next
            fast = fast.next.next
        prev.next = prev.next.next
        return head