본문 바로가기

풀어본 Algorithm 문제 정리

[OJ.leetcode] Linked List Cycle

https://oj.leetcode.com/problems/linked-list-cycle/

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?


**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     ListNode *next;

 *     ListNode(int x) : val(x), next(NULL) {}

 * };

 * 

 * ex: 1->2->1, 1->2->NULL, 1->NULL, 1->2->3->4->2

 */

class Solution {

public:

    bool hasCycle(ListNode *head) {

        ListNode* fastRunner = head;

        ListNode* slowRunner = head;


        while(fastRunner != NULL && fastRunner->next != NULL) {

            fastRunner = fastRunner->next;

            if(fastRunner == slowRunner) return true;

            fastRunner = fastRunner->next;

            

            slowRunner = slowRunner->next;

            if(fastRunner == slowRunner) return true;

        }//end while

        

        return false;

    }

};