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
'LeetCode > LeetCode75' 카테고리의 다른 글
[LeetCode 75] Easy - 206. Reverse Linked List (0) | 2024.11.15 |
---|---|
[LeetCode 75] Medium - 328. Odd Even Linked List (0) | 2024.11.15 |
[LeetCode 75] Medium - 649. Dota2 Senate (0) | 2024.11.14 |
[LeetCode 75] Easy - 933. Number of Recent Calls (0) | 2024.11.14 |
[LeetCode 75] Medium - 394. Decode String (0) | 2024.11.14 |