题意:判断连表中是否有回路。
思路:记录经过的每一个结点,看是否重复。
class Solution {
public:
bool hasCycle(ListNode *head) {
map<ListNode*, bool> m;
while(head) {
std::map<ListNode*, bool>::iterator it;
it = m.find(head);
if(it == m.end()) m[head] = true;
else return true;
head = head->next;
}
return false;
}
};
空间复杂度为O(1)的算法:
Use two pointers, walker and runner.
walker moves step by step. runner moves two steps at time.
if the Linked List has a cycle walker and runner will meet at some
point.