为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
示例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) {
ListNode now=head;
//过河拆桥,把走过的节点指向自己
while(now!=null){
if(now.next==now) return true;//如果最后是自己则有环
ListNode temp=now.next;
now.next=now;
now=temp;
}
return false;//如果最后是null则没有环
}
}
双指针
public boolean hasCycle(ListNode head) {
if (head == null) {
return false;
}
ListNode l1 = head, l2 = head.next;
while (l1 != null && l2 != null && l2.next != null) {
if (l1 == l2) {
return true;//如果有环,这两个指针一定会相遇
}
l1 = l1.next;//每次走一步
l2 = l2.next.next;//每次走两步
}
return false;
}