public static bool IsCycleLinkedList(Node head) { //Node current = root; //while (current != null) //{ // if (current.IsVisited) // { // Console.WriteLine(string.Format("First Cycle Node: {0}", current.ToString())); // return true; // } // current.IsVisited = true; // current = current.NextNode; //} Node n1 = head; var n2 = head; do { if (n1 == null || n2 == null || n2.NextNode == null) break; n1 = n1.NextNode; n2 = n2.NextNode.NextNode; } while (n1 != n2); if (n1 != null && n2 != null && n1 == n2) { Console.WriteLine(string.Format("First Cycle Node: {0}", n1.ToString())); return true; } return false; }
public void addedge(Node Start, Node End) { int StartIndex = Nodes.IndexOf(Start); int EndIndex = Nodes.IndexOf(End); int size = Nodes.Count; if (Adj == null) { Adj = new int[size,size]; } Adj[StartIndex, EndIndex] = 1; Adj[EndIndex, StartIndex] = 1; }
public Node unvisited(Node n) { int index = Nodes.IndexOf(n); int size = Nodes.Count; int j = 0 ; while (j < size) { if (Adj[index, j] == 1 && ((Node)Nodes[j]).visited == false) return ((Node)Nodes[j]); j++; } return null; }
public void insertnode(Node n) { n.visited = false; Nodes.Add(n); }