one line of code at a time

[leetcode] 876. Middle of the Linked List 본문

leetcode

[leetcode] 876. Middle of the Linked List

oloc 2024. 8. 22. 00:34

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

 

연결리스트의 중간 지점을 구하는 문제이다. 

fast, slow 이렇게 두 개의 포인터를 활용하면 쉽게 중간 지점을 구할 수 있다.

 

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

        while fast and fast.next:
            slow = slow.next # 한 칸씩
            fast = fast.next.next # 두 칸씩 
        return slow

 

 

참고

https://www.youtube.com/watch?v=A2_ldqM4QcY&t=21s