리트코드 하기 전에는 몰랐던 링크드 리스트 나오면 꼭 생각해야하는 fast/slow (runner/walker) 방식. 알아두면 유용.
내가 짠 코드
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *walker, *runner;
walker = head;
runner = head;
while(runner!=NULL && runner->next!=NULL){
walker = walker->next;
runner = runner->next->next;
if(walker==runner) return true;
}
return false;
}
};
'Problem Solving > 리트코드' 카테고리의 다른 글
[LeetCode] Longest Word in Dictionary through DeletingSolution (0) | 2021.02.22 |
---|---|
[LeetCode] Arithmetic SlicesSolution (0) | 2021.02.19 |
[LeetCode] Number of 1 Bits (0) | 2021.02.08 |
[LeetCode] Squares of a Sorted Array (0) | 2021.01.29 |
[LeetCode] 541. Reverse String II (0) | 2021.01.27 |