-
[LeetCode] Middle of the Linked List알고리즘 2022. 4. 23. 20:36
[LeetCode] Middle of the Linked List
풀이_#1
fast 와 slow 사용 fast 는 2칸씩, slow 는 1칸씩 이동하므로 n 번의 반복뒤에는 fast 는 2n 칸, slow 는 n 칸에 있고 fast가 끝일경우(2n = len) slow(n = len/2) 는 중간에 위치하게됨.# 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): """ :type head: ListNode :rtype: ListNode """ slow, fast = head, head while (fast and fast.next): slow = slow.next fast = fast.next.next return slow
'알고리즘' 카테고리의 다른 글
[LeetCode] 1342. Number of Steps to Reduce a Number to Zero (0) 2022.04.23 [LeetCode] The K Weakest Rows in Matrix (0) 2022.04.23 [LeetCode] Fizz Buzz (0) 2022.04.23 [백준] 최단 경로 (0) 2022.03.01 [프로그래머스] 가장 먼 노드 (0) 2022.02.10