Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路:
1.可以用hash表记录链表中每个节点的地址,然后遍历发现重复,即有环,否则到达末尾无环
2..空间复杂度常数,两指针,一个走一步,一个走两步,快的会追上慢的。
代码
class Solution { public: bool hasCycle(ListNode *head) { if(head==NULL) return false; if(head->next==NULL) return false; if(head->next==head) return true; //至少2个结点 ListNode* pOne=head; ListNode* pTwo=head; do{ if(pTwo->next==NULL) return false; pTwo=pTwo->next->next; pOne=pOne->next; if(pTwo==NULL) return false; } while(pOne!=pTwo); return true; } };