본문 바로가기

Problem Solving/리트코드

[LeetCode] Linked List Cycle

리트코드 하기 전에는 몰랐던 링크드 리스트 나오면 꼭 생각해야하는 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;
        
    }
};

leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/584/week-1-february-1st-february-7th/3627/