LeetCode/LeetCode75

[LeetCode 75] Medium - 2095. Delete the Middle Node of a Linked List

hyunkookim 2024. 11. 15. 14:28

2095. Delete the Middle Node of a Linked List

 

# 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 or not head.next:
            return None

        one_step = head
        two_step = head.next.next

        # while fast and fast.next: 조건을 사용하면 반복문은 마지막 노드 바로 전까지만 실행됨
        # 이유는 fast.next.next를 안전하게 참조하기 위해 마지막 노드에서는 반복을 종료해야 하기 때문
        while two_step and two_step.next:
            two_step = two_step.next.next
            one_step = one_step.next

        tmp = one_step
        one_step.next = one_step.next.next
        return head