2095. Delete the Middle Node of a Linked List

whitehousechef·2025년 3월 4일

https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/description/?envType=study-plan-v2&envId=leetcode-75

initial

So coming back from https://velog.io/@whitehousechef/Leetcode-2130.-Maximum-Twin-Sum-of-a-Linked-List-tuple-unpacking

the middle node of any linked list can be found via slow and fast pointers. The slow pointer, once finished iterating, will be pointing at the exact middle of list.

But here we dont reverse the first half of list. Instead we just traverse normally

solution

class Solution:
    def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        ori = head
        prev = None
        slow = fast = head
        while fast and fast.next:
            fast=fast.next.next
            prev,slow=slow,slow.next
        if prev:
            prev.next=slow.next
        else:
            return None
        return head

complexity

o(n) time
o(1) space

0개의 댓글