You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list.
The middle node of a linked list of size n is the ⌊n / 2⌋th node from the start using 0-based indexing, where ⌊x⌋ denotes the largest integer less than or equal to x.
For n = 1, 2, 3, 4, and 5, the middle nodes are 0, 1, 1, 2, and 2, respectively.
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/
#연결리스트
가운데 값을 구하기 위해, first와 second 두 개의 인덱스를 사용한다. second 인덱스는 first의 두 배만큼 전진하며, 그러므로 second가 노드의 마지막에 도달했을 때에 first는 가운데 값을 가리키게 된다. 연결 리스트의 노드 삭제는 next주소를 그 다음 노드로 바꾸는 것으로 해결된다.
# 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 head.next == None:
return None
first = head
second = head.next.next
while second and second.next:
first = first.next
second = second.next.next
first.next = first.next.next
return head
O(N)
Runtime: 1895 ms, faster than 91.25% of Python3 online submissions for Delete the Middle Node of a Linked List.
Memory Usage: 60.5 MB, less than 79.89% of Python3 online submissions for Delete the Middle Node of a Linked List.