(C++練習)141. Linked List Cycle

題目 :

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

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

大意 :

判斷 Link list 是否有cycle 條件.

 1 class Solution {
 2 public:
 3 
 4     bool hasCycle(ListNode *head) {
 5 
 6         ListNode * fast = head;
 7         ListNode * slow = head;
 8 
 9         while (fast != NULL && fast->next != NULL)
10         {
11             fast = fast->next->next;
12             slow = slow->next;
13             if (fast == slow)
14                 return true;
15         }
16 
17         return false;
18     }
19 };

猜你喜欢

转载自www.cnblogs.com/ollie-lin/p/10434008.html