one line of code at a time
[leetcode] 876. Middle of the Linked List 본문
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
참고
'leetcode' 카테고리의 다른 글
| [leetcode] 94. Binary Tree Inorder Traversal (0) | 2024.09.18 |
|---|---|
| [leetcode] 2095. Delete the Middle Node of a Linked List 파이썬 코드 (0) | 2024.08.22 |
| [leetcode] 547. Number of Provinces 파이썬 코드 (0) | 2024.08.18 |
| [leetcode] 113. Path Sum II 파이썬 코드 (0) | 2024.08.17 |
| [leetcode] 112. Path Sum 파이썬 코드 (0) | 2024.08.17 |