2017-03-25 55 views
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;  
    } 
} 

回答

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

不知道如何ü可以用if(ht.contains(tnode))当ü把关键INT ht.put(i, tnode);

0

包含Hashtable类的方法来检查对象的价值:

if(var4.value.equals(var1)) { 
        return true; 
       } 

所以在这种情况下,这个实现是正确的,并且如果它存在,它检测到了循环。

相关问题