给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
解法一:
/**
* 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) {
//第一步对链表进行校检,如果链表为空,或者只有一个节点,肯定构不成环
if(head == null || head.next == null){
return false;
}
//想象链表中有一个快指针,有一个慢指针,
//快指针每走两步,慢指针每次走一步,
//如果没有环,慢指针永远追不上快指针,快指针会一路领先到底
//如果有环,快指针会再多跑了一圈之后,追上慢指针,与之重逢
//为了区分开slow 和 fast节点,所以开始不能都用头节点来定义
ListNode slow = head;
ListNode fast = head.next;
while(slow != fast){
//快指针一路领先 走到了队尾
//他们始终没有重逢
if(fast.next == null || fast == null){
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
}
解法二:
/**
* 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) {
//定义一个set集合,将所有元素放进去
//进行遍历,如果某个元素被遍历了两次,则说明有环存在
//多态进行创建集合
Set hashSet = new HashSet();
while(head != null){
//只要某个节点在set中出现过,说明遍历到重复元素了
if(hashSet.contains(head)){
return true;
}
hashSet.add(head);
head = head.next;
}
return flase;
}