一.题目描述
输入单链表的头节点,判断单链表是否有环
二.题目思路
实现思路
1.定义fast和slow指针,并且设置初始值为单链表的头节点
2.让fast指针每次往后走两步,slow指针每次往后走一步。
3.循环指针步骤2,如果fast指针指向的节点为null或者fast指针指向节点的下一个节点为null,则证明单链表无环,如果fast指针和slow指针指向了同一个节点,则证明单链表有环
三.代码实现
Node类
public class Node {
//用于保存节点中的数据
private Object data;
//用于保存下一个节点的地址值
private Node next;
public Node(Object data) {
this.data = data;
}
public Node(Object data, Node next) {
this.data = data;
this.next = next;
}
public Object getData() {
return data;
}
public Node getNext() {
return next;
}
public void setData(Object data) {
this.data = data;
}
public void setNext(Node next) {
this.next = next;
}
}
/**
* 判断单链表是否有环 有环返回true 没有环返回false
* @return
*/
public static boolean hasLoop(Node headNode){
if (headNode == null){
return false;
}
//1.定义快慢指针,设置初始值为单链表的首节点
Node fast = headNode;
Node slow = headNode;
//2.循环执行 让fast指针走两步 slow指针走一步
while (fast != null && fast.getNext() != null){
fast = fast.getNext().getNext();
slow = slow.getNext();
if (fast == slow){
return true;
}
}
//执行到此处,证明单链表为无环单链表
return false;
}
测试方法
public static void main(String[] args) {
Node lastNode = new Node(44);
Node node3 = new Node(33,lastNode);
Node node2 = new Node(22,node3);
Node headnode = new Node(11,node2);
System.out.println(hasLoop(headnode));
Node node5 = new Node(88);
Node node4 = new Node(77,node5);
Node node6 = new Node(66,node4);
Node node7 = new Node(55,node6);
Node head = new Node(44,node7);
node5.setNext(node7);
System.out.println(hasLoop(head));
}
输出结果为 false true