문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음
단일 연결 리스트 head가 주어졌을 때, 연결 리스트의 중간 노드를 반환해라.
중간 노드가 두 개 있는 경우, 두 번째 노드를 반환해라.
#1
Input: head = [1, 2, 3, 4, 5]
Output: [3, 4, 5]
Explanation: 리스트의 중간 노드는 3이다.
#2
Input: head = [1, 2, 3, 4, 5, 6]
Output: [4, 5, 6]
Explanation: 리스트에는 값이 3과 4인 중간 노드가 두 개 있으므로 두 번째 노드를 반환한다.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode middleNode(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}