gpt4 book ai didi

java - 如何在java中使用hittable方法实现检测循环的函数

转载 作者:行者123 更新时间:2023-12-02 13:35:38 25 4
gpt4 key购买 nike

问题:

我想应用哈希表方法来检测java中的循环,并且我已经实现了一个方法。

Can anyone guide me is it correct or not?

实现:

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;
}
}

最佳答案

public void detectLoop1()
{
Node tnode = head;
Set nodes = new HashSet();

while (tnode != null)
{
System.out.print(tnode.data+"->");

if(!nodes.add(tnode)){
System.out.println("Found a Loop");
break;
}

tnode = tnode.next;
}
}

当你将 int 作为键时,不确定如何使用 if(ht.contains(tnode)) ht.put(i, tnode);

关于java - 如何在java中使用hittable方法实现检测循环的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43014009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com