题目
给你一个链表的头节点 head ,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。注意:pos 不作为参数进行传递 。仅仅是为了标识链表的实际情况。
如果链表中存在环 ,则返回 true 。 否则,返回 false 。
自解
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode current = head, tail = head;
while(tail != null){
tail = tail.next;
if(tail == null) break;
current = head;
while(current != tail && tail.next != current){
current = current.next;
}
if(tail.next == current)
return true;
}
return false;
}
}
边界条件current != tail
判断有误,写成了current.next != tail
,少考虑了一种尾部自己指向自己循环的情况,导致以下例子没有通过:
[-1,-7,7,-4,19,6,-9,-5,-2,-5]
9
只要弄清楚判断条件是 tail.next == current
且保证current在循环向后的过程中不超过tail所指节点,基本没什么困难。但此方法时间复杂度是O(n*n)级别的。
题解
看了题解,使用哈希表就不用从头再找了。应用HashSet。时间复杂度和空间复杂度都为O(n)。优化如下:
public class Solution {
public boolean hasCycle(ListNode head) {
Set<ListNode> set = new HashSet<ListNode>();
while(head != null){
if(!set.add(head))
return true;
head = head.next;
}
return false;
}
}
优雅!
题解二
Floyd判断法/龟兔赛跑算法
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null){
return false;
}
ListNode fast = head.next, slow = head;
while(fast != slow){
if(fast == null || fast.next == null){
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
}
学到了!很中!