LeetCode -- Linked List Cycle

题目链接

题意: 给出单链表, 判断是否存在环.

方法就是大步小步...

附上代码:

 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         if (head == NULL or head->next == NULL) { 13             return false; 14  } 15         ListNode *fast = head, *slow = head; 16         while (fast != NULL and fast->next != NULL) { 17             fast = fast->next; 18             if (fast == slow) { 19                 return true; 20  } 21             fast = fast->next; 22             if (fast == slow) { 23                 return true; 24  } 25             slow = slow->next; 26  } 27         return false; 28  } 29 };

 

 

你可能感兴趣的:(LeetCode)