1. 程式人生 > >LeetCode-141. Linked List Cycle

LeetCode-141. Linked List Cycle

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

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

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

題解:

class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode *p = head;
        while (p != NULL && p->next != NULL){
          p = p->next->next;
          head = head->next;
          if (p == head){
            return true;
          }
        }
        return false;
    }
};