// save elem to set, time O(n) space O(n) ListNode *detectCycle(ListNode *head){ ListNode* p = head; set<ListNode*> elem_set; while(p){ if (elem_set.find(p) != elem_set.end()) { return p; } elem_set.insert(p);//O(logN) p = p->next; } returnNULL; }
//fast and slow pointer ListNode *detectCycle1(ListNode *head){ ListNode *slow,*fast; slow = head; fast = head; while (slow!=NULL && fast->next!=NULL) { slow = slow->next; fast = fast->next->next; if (slow == fast) { //fast pointer go from and start of the link fast = head; while (fast != slow) { fast = fast->next; slow = slow->next; } return fast;//now both pointer is in the start of the citcle break; } } returnNULL; }
intmain(){ //input ListNode* res; ListNode *dummyhead,*head,*temp0,*temp1; dummyhead = new ListNode(-1); head = new ListNode(1); dummyhead ->next = head; temp0 = new ListNode(2); head->next = temp0; temp1 = new ListNode(4); temp0->next = temp1; temp1->next = temp0; //algorithm //res = detectCycle(head); res = detectCycle1(head); if (res == NULL) { cout<<"no circle"<<endl; } elsecout<<res->val<<endl; return0; }