141. 环形链表
问题
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数
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;
ListNode fast=head;
ListNode slow=head;
while(fast!=null&&fast.next!=null) {
fast=fast.next.next;
slow=slow.next;
if(slow==fast)
return true;
}
return false;
}
}