标签:for ptr node cycle size link fas ctc list
使用快慢指针,如果有环快慢指针一定会相遇
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *fast, *slow;
fast = slow = head;
while(slow && fast) {
slow = slow -> next;
if(fast -> next)
fast = fast -> next -> next; //bug处,如果没有if条件跳bug:fast幅值给了空值
else
return false;
if(fast == slow)
return true;
}
return false;
}
};
class Solution {//不是最优解 用了O(n)的空间
public:
ListNode *detectCycle(ListNode *head) {
ListNode *move_forward = head;
int count = 0;
set<ListNode *> iset;//bug处 最初把set类型设为struct listnode 不合法因为set元素必须为可比较类型
while(move_forward) {
iset.insert(move_forward);
++count;
if(iset.size() != count)
return move_forward;
move_forward = move_forward -> next;
}
return nullptr;
}
};
leetcode 141 142 Linked List Cycle I/II
标签:for ptr node cycle size link fas ctc list
原文地址:http://www.cnblogs.com/bloomingFlower/p/7663402.html