876. Middle of the Linked List
Easy
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.
♬idea
- 런너를 이용해 fast 런너가 끝에 도착했을 때 slow 런너가 도달한 노드를 반환한다.
- 배열을 활용한다.
1. 런너를 이용한 풀이
# 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 = fast = head
#런너 사용
while fast and fast.next:
fast = fast.next.next
slow = slow.next
return slow
2. 배열을 이용한 풀이
# 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]:
arr = [head]
while arr[-1].next:
arr.append(arr[-1].next)
return arr[len(arr)//2]
'Coding Test > leetcode_with_pythonAlgorithmInterview' 카테고리의 다른 글
234. 팰린드롬 연결 리스트 (0) | 2022.09.18 |
---|---|
206. 역순 연결 리스트 (0) | 2022.09.18 |
42. 빗물 트래핑 (0) | 2022.09.16 |
121. 주식을 사고팔기 가장 좋은 시점 (0) | 2022.09.16 |
561. 배열 파티션Ⅰ (0) | 2022.09.15 |