首页 > 代码库 > 141. Linked List Cycle

141. Linked List Cycle

题目:

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

思路:

设置一个快指针,一个慢指针。快指针的步长为2,慢指针的步长为1。快指针和慢指针终会进入环中并在环中循环,最终相遇。

判断条件:需要判断快慢指针是否为NULL,以及快指针指向的下一个节点是否为空。

代码:

技术分享
 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     bool hasCycle(ListNode *head) {
12         ListNode *fast = head;
13         ListNode *slow = head;
14         while ((fast != NULL) && (slow != NULL) && (fast->next != NULL)) {
15             fast = fast->next->next;
16             slow = slow->next;
17             if (fast == slow) {
18                 return true;
19             }
20         }
21         return false;
22     }
23 };
View Code

 

141. Linked List Cycle