https://leetcode.com/problems/middle-of-the-linked-list/description/

 

Middle of the Linked List - LeetCode

Can you solve this real interview question? Middle of the Linked List - Given the head of a singly linked list, return the middle node of the linked list. If there are two middle nodes, return the second middle node.   Example 1: [https://assets.leetcode.

leetcode.com

 

이것도 slow & fast pointer 문제다!

slow는 한칸, fast는 두칸씩 이동시키면서 fast가 끝에 다다랐는지 보면된다.

 

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
        slow = head
        fast = head

        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next

        return slow

+ Recent posts