帶環鏈表
給定一個鏈表,判斷它是否有環。
給出 -21->10->4->5, tail connects to node index 1,返回 true
不要使用額外的空間
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/*
* @param head: The first node of linked list.
* @return: True if it has a cycle, or false
*/
bool hasCycle(ListNode * head) {
// write your code here
ListNode *fast=head,*slow=head;
while(fast&&fast->next)
{
fast=fast->next->next;
slow=slow->next;
if(slow==fast)
return true;
}
return false;
}
};
這裏還有個求環形入口的問題,日後有時間再整理