https://leetcode.com/problems/middle-of-the-linked-list/
Input:[1,2,3,4,5]
Output:Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
두칸씩 옮겨지는 fast node 와 한칸씩 옮겨지는 slow node 로 중간 지점을 찾는다.
class Solution {
public:
ListNode* middleNode(ListNode* head) {
if(head == NULL) return NULL;
ListNode* fastLink = head;
ListNode* slowLink = head;
while(fastLink)
{
if(fastLink->next)
{
fastLink = fastLink->next->next;
slowLink = slowLink->next;
}
else
break;
}
return slowLink;
}
};