题目描述
解法
解法一
暴力解法:题目中链表中节点的数目范围是0到10的4次方,我们可以设置一个num记录遍历的节点数,如果超过10000,说明有环
/**
* 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) {
//暴力解法,题目中链表中节点的数目范围是0到10的4次方,我们可以设置一个num记录遍历的节点数,如果超过10000,说明有环
int num = 0;
ListNode curr = head;
while (curr != null) {
num ++;
curr = curr.next;
if (num > 10000) {
return true;
}
}
return false;
}
}
解法二
思想
这个其实也是自己最初的想法就是在遍历链表的过程中如果遍历到以前访问过的节点,说明链表中有环。
HashSet是Set类的一个子类,并且直接实现了Set接口
HashSet的对象有一个add方法用于向Set集合中添加元素,因为HashSet集合不允许有重复的元素,所以如果添加HashSet集合中没有的元素会添加成功返回true,如果添加HashSet集合中已经有的元素会返回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) {
//哈希表法
Set<ListNode> set = new HashSet<ListNode>();
ListNode curr = head;
while (curr != null) {
if (!set.add(curr)) { //如果往哈希表里添加节点失败说明之前已经这个节点之前已经被放入哈希中,也就是链表指向了访问过的节点,说明有环
return true;
}
curr = curr.next;
}
return false;
}
}
解法三
我们可以看一下「Floyd 判圈算法」(又称龟兔赛跑算法)
假想「乌龟」和「兔子」在链表上移动,「兔子」跑得快,「乌龟」跑得慢。当「乌龟」和「兔子」从链表上的同一个节点开始移动时,如果该链表中没有环,那么「兔子」将一直处于「乌龟」的前方;如果该链表中有环,那么「兔子」会先于「乌龟」进入环,并且一直在环内移动。等到「乌龟」进入环时,由于「兔子」的速度快,它一定会在某个时刻与乌龟相遇,即套了「乌龟」若干圈。
我们可以根据上述思路来解决本题。
快慢指针法:分别定义fast和slow指针,从头节点出发,fast指针每次移动两个节点,slow指针每次一定一个节点,如果fast和slow指针在途中相遇,说明这个链表有环。
/**
* 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) {
//快慢指针法:分别定义fast和slow指针,从头节点出发,fast指针每次移动两个节点,slow指针每次一定一个节点,如果fast和slow指针在途中相遇,说明这个链表有环
ListNode slow = head;
ListNode fast = head;
int n = 0;
if (head == null) {
return false;
}
if (head.next == head) {
return true;
}
while (fast != null){
n ++;
fast = fast.next;
if (n % 2 == 0) {
slow = slow.next;
}
if (fast == slow) {
return true;
}
}
return false;
}
}