验证中...
Languages: Java
Categories: 其他
Latest update 2019-06-20 22:11
LoopInLinkedlist.java
Raw Copy
package lab1505;
import java.util.HashSet;
import org.junit.jupiter.api.Test;
public class LoopInLinkedlist{
class Node{
int value;
Node next;
public Node(int value,Node next){
this.value = value;
this.next = next;
}
}
@Test
public void run(){
Node first = new Node(1,null);
Node second = new Node(2,null);
Node third = new Node(3,null);
first.next = second;
second.next = third;
System.out.println("first linkedlist: "+hasLoop(first)); //first linkedlist: false
third.next = first;
System.out.println("second linkedlist: "+hasLoop(first)); //second linkedlist: true
}
public boolean hasLoop(Node node){
HashSet<Node> set = new HashSet<>();
while(node!=null){
if (set.contains(node)){
return true;
}else{
set.add(node);
}
node = node.next;
}
return false;
}
}

Comment list( 0 )

You need to Sign in for post a comment

Help Search

183227_9af5e6a8_1826025 111910_4d91f001_1826025