判断链表是否为环形
思路:
定义两个指针fast、slow, 一次循环中让fast走两步,slow走一步。
看两者有无相遇的机会(判断两个指针是否为同一节点),相等则为同一个节点-->链表为环形
判断链表是否为环形的实现
package com.codezs.datastruct.mylinkedlist;
public class LinkListCircle {
//判断链表是否为环形
public boolean checkCircle(Node node){
//如果该节点为null 则不为环形链表
if (node == null) return false;
Node fast = node.next;
Node slow = node;
while (fast != null && fast.next !=null){
fast = fast.next.next;
slow = slow.next;
if (fast == slow) return true;
}
return false;
}
}
节点类的实现
package com.codezs.datastruct.mylinkedlist;
public class Node<T> {
T data;
Node<T> next;
Node(Node<T> next) {
this.next = next;
}
public Node(T data, Node<T> next) {
this.data = data;
this.next = next;
}
public T getData(){
return data;
}
public Node<T> getNext(){
return next;
}
public void setNext(Node<T> next){this.next = next;}
}