LeetCode Linked List Cycle 单链表环

题意:给一个单链表,判断其是否出现环!

思路:搞两个指针,每次,一个走两步,另一个走一步。若有环,他们会相遇,若无环,走两步的指针必定会先遇到NULL。

 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head) return false;
ListNode * one=head, *two=head->next;
while(two && two->next && one!=two)
{
one=one->next;
two=two->next->next;
}
if(two&&two->next) return true;
else return false;
}
};

AC代码

上一篇:如何直接执行js代码


下一篇:mysql 8.X.X版本多个ip限制访问