We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Linked Lists: Detect a Cycle
- Discussions
Linked Lists: Detect a Cycle
Linked Lists: Detect a Cycle
+ 0 comments C++
bool has_cycle(Node* head) { // Complete this function // Do not write the main method Node* slowerPtr = head; Node* fasterPtr = head; if ( (head == nullptr) || (head->next == nullptr) ){ return false; } while( (fasterPtr != nullptr) && (fasterPtr->next != nullptr) ){ slowerPtr = slowerPtr->next; fasterPtr = fasterPtr->next->next; if (slowerPtr == fasterPtr){ return true; } } return false; }
+ 0 comments Cpp solution with O(n) complexity.
bool has_cycle(Node* head) { map<Node*, int> ptrMap; Node *currPtr = head; while(currPtr != nullptr) { if(ptrMap.find(currPtr) != ptrMap.end()) { return true; } ptrMap[currPtr]++; currPtr = currPtr->next; } return false; }
+ 0 comments bool has_cycle(Node* head) { Node *s=head,*f=head; while(s && f->next && f->next->next) { s=s->next; f=f->next->next; if(s==f) { return 1; } } return 0;
+ 0 comments /* Detect a cycle in a linked list. Note that the head pointer may be 'NULL' if the list is empty.
A Node is defined as: struct Node { int data; struct Node* next; } */
bool has_cycle(Node* head) { // Complete this function // Do not write the main method if ( NULL == head ) return false;
Node *temp = head; Node **visit = new Node *[200]; int num=0; while (temp ) { for (int i=0; i<num; i++) { if ( visit[i] == temp ) { delete [] visit; return true; } } visit[num++] =temp; temp = temp->next; } return false;
}
+ 0 comments Javascript:
function checkCircle(nodes) { const preNodes = []; let node = nodes; do { preNodes.push(node); node = node.next; if (preNodes.some(n => n === node)) { return true; } } while (node !== null) return false; }
Load more conversations
Sort 510 Discussions, By:
Please Login in order to post a comment