如果面试时,遇到这个题目,先喝口水压压惊,回想一下,咱们小时候念小学时,数学老师最喜欢的一类题目:
跑道上,2个运动员,1个速度是3m/s,1个速度是5m/s,同一起点起跑后,多久运动员2会再次遇到运动员1?是不是感觉异曲同工? 这2个速度不同的运动员,相当于就是快/慢2个指针
代码语言:javascript复制@Data
class Node {
private String value;
private Node next;
public Node(String value) {
this.value = value;
}
}
@Test
public void isLoopLink() {
Node a = new Node("a");
Node b = new Node("b");
Node c = new Node("c");
Node d = new Node("d");
a.next = b;
b.next = c;
c.next = d;
d.next = b;
int loopSize = 0, meetCount = 0;
Node slow = a, fast = a;
while (slow.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == null || slow == null) {
System.out.println("it is not a loop link");
break;
}
if (fast.value.equalsIgnoreCase(slow.value)) {
//首次相遇
meetCount = 1;
if (meetCount > 1) {
//再次相遇
System.out.println("it is a loop link,loopSize:" loopSize);
break;
}
}
if (meetCount == 1) {
//首次遇到后,开始数环的节点个数
loopSize = 1;
}
}
}