题目
- 判断单链表是否存在环,如果存在环求环长度、求环入口
解法
- 创建Node链表结构
class Node {
// 指针
Node next;
// 数据
int data;
public Node(int data) {
this.data = data;
}
}
- 判断是否有环
// 使用两个指针,重合表示有环
/**
* 是否是回环
* @param node
* @return
*/
public boolean isCycleLink(Node node) {
if (node == null) return false;
// 慢指针
Node slow = node;
// 快指针
Node fast = node;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
- 结合上一个方法求环长度
/**
* 获取环长度
*
* @param node
* @return
*/
public int getCycleLength(Node node) {
int length = 0;
if (!isCycleLink(node)) return length;
Node slow = node;
Node fast = node;
while (fast != null && fast.next != null) {
length++;
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
break;
}
}
return length;
}
- 求环入口
双指针方式
/**
* 获取环的入口 双指针方法
*
* @param node
* @return
*/
public Node getCyclePoint(Node node) {
if (!isCycleLink(node)) return null;
Node slow = node;
Node fast = node;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return fast;
}
}
return fast;
}
单指针方式
/**
* 获取环入口方法二
*
* @param node
* @return
*/
public Node getCyclePointTwo(Node node) {
if (!isCycleLink(node)) return null;
Node current = node;
while (current != null && current.next != null) {
current = current.next;
if (current == node) {
return current;
}
}
return current;
}