0
问题来实现的功能来检测一个循环:如何使用hittable方法在Java中
我想申请哈希表的方法来检测Java中的循环,我已经实现了它的方法。
任何人都可以指导我是否正确?
实现:
public void detectLoop1()
{
Node tnode = head;
int i=0;
//Initialize the HashTable
Hashtable ht=new Hashtable();
//Traverse the list and while traversing if you find the address of
//the hittable is already in hashtable break the loop else insert the elements in hashtable.
while (tnode != null)
{
System.out.print(tnode.data+"->");
if(ht.contains(tnode)){
System.out.println("Found a Loop");
break;
}
ht.put(i, tnode);
i++;
tnode = tnode.next;
}
}