PS

Leetcode 876. Middle of the Linked List

Bryan Lee 2022. 4. 25. 02:31

문제 이해

- 링크드 리스트의 중간부부터 반환하라. 

 

해결 전략

- 두 개의 링크드 리스트(slow, fast)를 선언하고, 각각에 head를 대입한다.

- while문을 통해 slow=slow.next, fast=fast.next.next로 이동하면서,

   fast와 fast.next중 하나가 null일때까지 이동한다.

- slow를 리턴한다. 

 

구현

class Solution {
    public ListNode middleNode(ListNode head) {
        
       ListNode slow = head;
       ListNode fast = head;
        
       while(fast != null && fast.next != null){
           slow = slow.next;
           fast = fast.next.next;
       } 
        
       return slow;  
        
    }
}

 

피드백

- 비슷한 풀이라고 하더라도, 견고한 풀이가 좋은 풀이다.