int main() { struct ListNode *l1 = (struct ListNode *)calloc(5, sizeof(struct ListNode)); struct ListNode *p = l1; p->val = 1; p->next = l1 + 1; p = p->next; p->val = 2; p->next = l1 + 2; p = p->next; p->val = 3; p->next = l1 + 3; p = p->next; p->val = 4; p->next = l1 + 4; p = p->next; p->val = 5; p->next = NULL; /* no cycle */ printf("%d\n", hasCycle(l1)); /* no cycle */ printf("%d\n", hasCycle(l1 + 4)); p->next = l1 + 2; /* cycle */ printf("%d\n", hasCycle(l1)); /* no cycle */ printf("%d\n", hasCycle(NULL)); return 0; }
shared_ptr<ListNode<int>> OverlappingLists::overlappingLists (shared_ptr<ListNode<int>> list1, shared_ptr<ListNode<int>> list2) { auto cycleEntrance1 = hasCycle(list1); // could be nullptr auto cycleEntrance2 = hasCycle(list2); size_t len1 = 0, len2 = 0; auto ptr1 = list1, ptr2 = list2; while(ptr1 != cycleEntrance1) { ++len1; ptr1 = ptr1->next; } // If cycle1 and cycle2 are not same cycle, need break the while bool secondCycle = false; while (ptr2 && ptr2 != cycleEntrance1) { if (ptr2 == cycleEntrance2) { if (secondCycle) return nullptr; secondCycle = true; } ++len2; ptr2 = ptr2->next; } size_t diff = 0; if (len1 < len2) { diff = len2 - len1; auto tmp = list1; list1 = list2; list2 = tmp; } else { diff = len1 - len2; } while (--diff) list1 = list1->next; while (ptr1 && ptr2) { if (ptr1 == ptr2) return ptr1; ptr1 = ptr1->next; ptr2 = ptr2->next; } return nullptr; }
bool testCase4() { ListNode* head=new ListNode(1); head->next=new ListNode(3); // return hasCycle(head); }
void test_hasCycle() { int a[] = { 1, 2, 3, 4 }; int b[] = { 1, 2, 3 }; int c[] = { 1, 2 }; int d[] = { 1 }; ListNode *p1 = createList(a, sizeof(a) / sizeof(a[0])); ListNode *p2 = createList(b, sizeof(b) / sizeof(b[0])); ListNode *p3 = createList(c, sizeof(c) / sizeof(c[0])); ListNode *p4 = createList(d, sizeof(d) / sizeof(d[0])); printf("%d\n", hasCycle(p1)); printf("%d\n", hasCycle(p2)); printf("%d\n", hasCycle(p3)); printf("%d\n", hasCycle(p4)); }
bool hasCycle(int root, bool* hasBeenVisited) { auto current = edges[root]; while (current != nullptr) { if (hasBeenVisited[current->verticeTo] == true) { return true; } hasBeenVisited[current->verticeTo] = true; if (hasCycle(current->verticeTo, hasBeenVisited) == true) { return true; } hasBeenVisited[current->verticeTo] = false; current = current->next; } return false; }
/* @brief depth first search to detect cycle * */ void DirectedCycle::dfs(const Digraph &dg, int v){ marked[v] = true; onStack[v] = true; list<int>::const_iterator it; for( it = (dg.adj(v)).begin(); it != dg.adj(v).end(); ++it){ //there exists a cycle if( hasCycle() ){ return ; } if( !marked[*it] ){ edgeTo[*it] = v; dfs(dg, *it); }else{ //cycle detected if( onStack[*it] ){ for(int u = v; u != *it; u = edgeTo[u] ){ cyc.push_front(u); } cyc.push_front(*it); cyc.push_front(v); } } } //v has been searched onStack[v] = false; }
string alienOrder(vector<string>& words) { int n = words.size(); if (n == 0) return ""; graph = vector<vector<bool>>(N, vector<bool>(N, false)); degree = vector<int>(N, 0); appears = set<int>(); for (int i = 0; i < n; ++i) { for (int j = 0; j < words[i].size(); ++j) appears.insert(offset(words[i][j])); } for (int i = 1; i < n; ++i) { int j = 0; int length = min(words[i - 1].size(), words[i].size()); while (j < length) { int from = offset(words[i - 1][j]); int to = offset(words[i][j]); if (words[i - 1][j] != words[i][j]) { if (!graph[from][to]) { graph[from][to] = true; degree[to]++; } break; } j++; } } if (hasCycle()) return ""; string ans = ""; while (true) { int from = -1; for (auto i = appears.begin(); i != appears.end(); ++i) { if (degree[*i] == 0) { from = *i; break; } } if (from == -1) break; appears.erase(from); for (int to = 0; to < N; ++to) { if (graph[from][to]) degree[to]--; } ans += (char)('a' + from); } for (auto i = appears.begin(); i != appears.end(); ++i) { int from = *i; ans += (char)('a' + from); } return ans; }
bool hasCycle(vector<vector<int>>& neighbors, int kid, int parent, vector<bool>& visited) { if (visited[kid]) return true; visited[kid] = true; for (auto neigh : neighbors[kid]) if (neigh != parent && hasCycle(neighbors, neigh, kid, visited)) return true; return false; }
int main(int argc, char **argv) { struct ListNode *head; int a[] = {1,2,3,4,5}; mk_list(&head, a, 5); //head->next->next = head; printf("%d\n", hasCycle(head)); printf("%d\n", detectCycle(head)->val); return 0; }
struct ListNode *detectCycle(struct ListNode *head) { struct ListNode *node; while (head != NULL) { if (true == hasCycle(head)) { node = head->next; head->next = NULL; if (false == hasCycle(node)) { return head; } else { head = node; } } head = head->next; } return NULL; }
int main(int argc, char* argv[]) { auto graph = new Graph(4); graph->addEdge(1, 2); graph->addEdge(1, 3); graph->addEdge(1, 4); graph->addEdge(2, 4); std::cout << "Graph does not has cycle: " << graph->hasCycle() << std::endl; graph = new Graph(5); graph->addEdge(1, 2); graph->addEdge(1, 3); graph->addEdge(2, 4); graph->addEdge(4, 5); graph->addEdge(5, 1); std::cout << "Graph has cycle: " << graph->hasCycle() << std::endl; }
int main() { struct ListNode p1, p2, p3; struct ListNode q1, q2, q3; struct ListNode r1, r2, r3, r4, r5; struct ListNode s1, s2; struct ListNode t; p1.next = &p2; p2.next = &p3; p3.next = NULL; q1.next = &q2; q2.next = &q3; q3.next = &q1; r1.next = &r2; r2.next = &r3; r3.next = &r4; r4.next = &r5; r5.next = &r3; s1.next = &s2; s2.next = &s1; t.next = &t; print(hasCycle(&p1)); print(hasCycle(&q1)); print(hasCycle(&r1)); print(hasCycle(&s1)); print(hasCycle(&t)); print(hasCycle(NULL)); return 0; }
int main(int argc, char const *argv[]) { List L1, L2, L3; Position P; L1 = CreateList(1); PrintList(L1); printf("%d\n", hasCycle(L1)); for (P = L1; P -> next != NULL; P = P -> next); P -> next = L1; printf("%d\n", hasCycle(L1)); L2 = CreateList(5); PrintList(L2); printf("%d\n", hasCycle(L2)); for (P = L2; P -> next != NULL; P = P -> next); P -> next = L2; printf("%d\n", hasCycle(L2)); L3 = CreateList(2); PrintList(L3); printf("%d\n", hasCycle(L3)); for (P = L3; P -> next != NULL; P = P -> next); P -> next = L3; printf("%d\n", hasCycle(L3)); return 0; }
void VsRegistry::loadTime(VsGroup* group) { VsLog::debugLog() <<"VsRegistry::loadTime() - Group is NULL?" << "'" << group << "'" <<std::endl; if (!group) { VsLog::debugLog() <<"VsRegistry::loadTime() - Group is NULL?" <<std::endl; return; } //try to load a value for "time" double foundTime = -1.0; VsAttribute* timeAtt = group->getAttribute(VsSchema::timeAtt); if (timeAtt) { std::vector<float> in; int err = timeAtt->getFloatVectorValue(&in); if (err < 0) { VsLog::debugLog() <<"VsRegistry::loadTime(): Error " <<err <<" while trying to load time attribute." <<std::endl; } else { foundTime = in[0]; VsLog::debugLog() <<"VsRegistry::loadTime() - loaded time: " <<foundTime <<std::endl; } } //try to load a value for "cycle" int foundCycle = -1; VsAttribute* cycleAtt = group->getAttribute(VsSchema::cycleAtt); if (cycleAtt) { std::vector<int> in; int err = cycleAtt->getIntVectorValue(&in); if (err < 0) { VsLog::debugLog() <<"VsRegistry::loadTime(): Error " <<err <<" while trying to load cycle attribute." <<std::endl; } else { foundCycle = in[0]; VsLog::debugLog() <<"VsRegistry::loadTime() - loaded cycle: " <<foundCycle <<std::endl; } } //check for existing time data, and compare if ((foundTime != -1) && hasTime() && (foundTime != getTime())) { VsLog::warningLog() <<"VsRegistry::loadTime() - was asked to load time data again, but time data already exists." <<std::endl; VsLog::warningLog() <<"VsRegistry::loadTime() - and is in conflict: " <<foundTime <<" vs " <<getTime() <<std::endl; } else { timeValue = foundTime; } if ((foundCycle != -1) && hasCycle() && (foundCycle != getCycle())) { VsLog::warningLog() <<"VsRegistry::loadTime() - was asked to load cycle data again, but cycle data already exists." <<std::endl; VsLog::warningLog() <<"VsRegistry::loadTime() - and is in conflict: " <<foundCycle <<" vs " <<getCycle() <<std::endl; } else { cycle = foundCycle; } }
bool validTree(int n, vector<pair<int, int>>& edges) { vector<vector<int>> neighbors(n); for (auto e : edges) { neighbors[e.first].push_back(e.second); neighbors[e.second].push_back(e.first); } vector<bool> visited(n, false); if (hasCycle(neighbors, 0, -1, visited)) return false; for (bool v : visited) if (!v) return false; return true; }
edge_descriptor addEdge( const vertex_descriptor& v1, const vertex_descriptor& v2, const Edge& prop ) { //TUTTLE_TCOUT_VAR2( v1, instance(v1) ); //TUTTLE_TCOUT_VAR2( v2, instance(v2) ); const edge_descriptor addedEdge = boost::add_edge( v1, v2, prop, _graph ).first; if( hasCycle() ) { removeEdge( addedEdge ); BOOST_THROW_EXCEPTION( exception::Logic() << exception::user() + "Connection error: the graph becomes cyclic while connecting \"" + instance(v1) + "\" to \"" + instance(v2) + "\"" ); } return addedEdge; }
/* * So, the idea is: * 1) Using the cycle-chcking algorithm. * 2) Once p1 and p1 meet, then reset p1 to head, and move p1 & p2 synchronously * until p1 and p2 meet again, that place is the cycle's start-point */ ListNode *detectCycle(ListNode *head) { if (hasCycle(head)==false){ return NULL; } p1 = head; while (p1!=p2) { p1 = p1->next; p2 = p2->next; } return p1; }
bool hasCycle(int node, vector<vector<int>> const& adj, vector<int>& color, vector<int>& result) { color[node] = grey; for(int i = 0; i < (int)adj[node].size(); ++i) { int neigh = adj[node][i]; if(color[neigh] == grey) { return true; } if(color[neigh] == white) { if(hasCycle(neigh, adj, color, result)) { return true; } } } color[node] = black; result.push_back(node); return false; }
bool hasCycle() { bool* hasBeenVisited = (bool*)malloc((numberOfVertices + 1)*sizeof(bool)); memset(hasBeenVisited, false, (numberOfVertices + 1)*sizeof(bool)); for (auto v = 1; v <= numberOfVertices; ++v) { if (hasBeenVisited[v] == false) { hasBeenVisited[v] = true; if (hasCycle(v, hasBeenVisited) == true) { return true; } } } return false; }
int main(int argc, char **argv) { int i, count = argc - 1; struct ListNode *head = NULL, *p, *prev; for (i = 0; i < count; i++) { p = malloc(sizeof(*p)); p->val = atoi(argv[i + 1]); p->next = NULL; if (head == NULL) { head = p; } else { prev->next = p; } prev = p; } p->next = head; printf("%s\n", hasCycle(head) ? "true" : "false"); return 0; }
edge_descriptor addEdge( const vertex_descriptor& v1, const vertex_descriptor& v2, const Edge& prop ) { if( hasEdge( v1, v2, prop.getInAttrName() ) ) { BOOST_THROW_EXCEPTION( exception::Logic() << exception::dev() + "Can't add Edge. There is already a connection from \"" + instance(v1) + "\" to \"" + instance(v2) + "/" + prop.getInAttrName() + "\"" ); } //TUTTLE_LOG_VAR2( TUTTLE_TRACE, v1, instance(v1) ); //TUTTLE_LOG_VAR2( TUTTLE_TRACE, v2, instance(v2) ); const edge_descriptor addedEdge = boost::add_edge( v1, v2, prop, _graph ).first; if( hasCycle() ) { removeEdge( addedEdge ); BOOST_THROW_EXCEPTION( exception::Logic() << exception::user() + "Connection error: the graph becomes cyclic while connecting \"" + instance(v1) + "\" to \"" + instance(v2) + "\"" ); } return addedEdge; }
bool isValidTopSort(std::vector<int> order, Graph const * graph){ if (hasCycle(graph)) return order.empty(); int n = graph->getVerticesNumber(); if (order.size() != n) return false; std::vector<int> index(n); for (int i = 0; i < n; ++i) index[order.at(i)] = i; for (int i = 0; i < n; ++i){ for (int &to : graph->getIncidenceList(i)) if (index[i]>index[to]) return false; } return true; }
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) { int edges = prerequisites.size(); vector<vector<int>> adj; adj.resize(numCourses); for(int i = 0; i < edges; ++i) { int u = prerequisites[i].first; int v = prerequisites[i].second; adj[u].push_back(v); } vector<int> result; vector<int> color(numCourses, white); for(int i = 0; i < numCourses; ++i) { if(color[i] == white) { if(hasCycle(i, adj, color, result)) { result = vector<int>(); return result; } } } return result; }
// throws on cycle void c_BlockableWaitHandle::blockOn(c_WaitableWaitHandle* child) { setState(STATE_BLOCKED); assert(getChild() == child); // detect complete cycles if (UNLIKELY(hasCycle(child))) { reportCycle(child); assert(false); } // make sure the child is going to do some work // throws if cross-context cycle found if (isInContext()) { child->enterContext(getContextIdx()); } // extend the linked list of parents m_nextParent = child->addParent(this); // increment ref count so that we won't deallocated before child calls back incRefCount(); }
void DirectedCycle::dfs(DirGraph& G, int v){ onStack[v] = true; marked[v] = true; Bag *Temp = G.Iterator(v); Temp->BeginIter(); int w; while(Temp->HasNext()){ w = Temp->Next(); if(hasCycle()) return; else{ if(!marked[w]){ edgeTo[w] = v; dfs(G,w); } else if (onStack[w]){ for(int x = v; x != w; x = edgeTo[x]) cycle.push_front(x); cycle.push_front(w); cycle.push_front(v); } } } onStack[v] = false; }
int main(){ int arr[] = {1,2,3,4,5}; ListNode *head = init_list(arr, sizeof(arr)/sizeof(int)); cout<<hasCycle(head)<<endl; return 0; }
bool testCase3() { ListNode* head=new ListNode(1); // return hasCycle(head); }
ListNode *detectCycle(ListNode *head) { ListNode *meetNode = hasCycle(head); if (!meetNode) return NULL; return enterCycle(head, meetNode); }