문제 이해
- 링크드 리스트의 중간부부터 반환하라.
해결 전략
- 두 개의 링크드 리스트(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;
}
}
피드백
- 비슷한 풀이라고 하더라도, 견고한 풀이가 좋은 풀이다.
'PS' 카테고리의 다른 글
Leetcode 234. Palindrome Linked List (1) | 2022.04.26 |
---|---|
Leetcode 203. Remove Linked List Elements (1) | 2022.04.26 |
Leetcode 2207. Maximize Number of Subsequences in a String (0) | 2022.04.25 |
Leetcode 2233. Maximum Product After K Increments (0) | 2022.04.24 |
Leetcode 2211. Count Collisions on a Road (0) | 2022.04.24 |