141.环形链表
141.环形链表
给你一个链表的头节点 head ,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。注意:pos 不作为参数进行传递 。仅仅是为了标识链表的实际情况。
如果链表中存在环 ,则返回 true 。 否则,返回 false 。
输入:head = [3,2,0,-4], pos = 1;
输出:true
解释:链表中有一个环,其尾部连接到第二节点3 -> 2 -> 0 -> -4
|_________________________________|提示:
- 链表中节点的数目范围是
[0, 104]-105 <= Node.val <= 105pos为-1或者链表中的一个 有效索引 。
java :
// 解法1: 暴力解法,纯属娱乐
/**
思路:因为结点数目范围是[0,10^4], 比较小,所以直接遍历全部即可
*/
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode tmp = head;
float count = 10 * 10 * 10 * 10;
int length = 0;
if(tmp == null) return false;
while(tmp != null){
length++;
if(length > count)
return true;
tmp = tmp.next;
}
return false;
}
}
// 解法2:因为有环,所以可以使用快慢指针来解决
/**
思路:存在环,所以可以使用两个指针,一个快,一个满,如果有环,那么他们终将相遇,否则则不会,其中原理,在于伟大的数学
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null){
return false;
}
ListNode tmpA = head;
ListNode tmpB = head;
while(tmpB != null && tmpB.next != null){
tmpA = tmpA.next;
tmpB = tmpB.next.next;
if(tmpA == tmpB) return true;
}
return false;
}
}

浙公网安备 33010602011771号