MCPcopy Create free account
hub / github.com/crossoverJie/JCSprout / LinkLoop

Class LinkLoop

src/main/java/com/crossoverjie/algorithm/LinkLoop.java:11–60  ·  view source on GitHub ↗

Function:是否是环链表,采用快慢指针,一个走的快些一个走的慢些 如果最终相遇了就说明是环 就相当于在一个环形跑道里跑步,速度不一样的最终一定会相遇。 @author crossoverJie Date: 04/01/2018 11:33 @since JDK 1.8

Source from the content-addressed store, hash-verified

9 * @since JDK 1.8
10 */
11public class LinkLoop {
12
13 public static class Node{
14 private Object data ;
15 public Node next ;
16
17 public Node(Object data, Node next) {
18 this.data = data;
19 this.next = next;
20 }
21
22 public Node(Object data) {
23 this.data = data ;
24 }
25 }
26
27 /**
28 * 判断链表是否有环
29 * @param node
30 * @return
31 */
32 public boolean isLoop(Node node){
33 Node slow = node ;
34 Node fast = node.next ;
35
36 while (slow.next != null){
37 Object dataSlow = slow.data;
38 Object dataFast = fast.data;
39
40 //说明有环
41 if (dataFast == dataSlow){
42 return true ;
43 }
44
45 //一共只有两个节点,但却不是环形链表的情况,判断NPE
46 if (fast.next == null){
47 return false ;
48 }
49 //slow走慢点 fast走快点
50 slow = slow.next ;
51 fast = fast.next.next ;
52
53 //如果走的快的发现为空 说明不存在环
54 if (fast == null){
55 return false ;
56 }
57 }
58 return false ;
59 }
60}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected