题目:
给定一个链表,判断它是否有一个循环。
为了在给定的链表中表示一个循环,我们使用一个整数pos,它表示tail连接到的链表中的位置(0索引)。如果pos为-1,则链表中没有循环。
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos
which represents the position (0-indexed) in the linked list where tail connects to. If pos
is -1
, then there is no cycle in the linked list.
Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a cycle in the linked list, where tail connects to the second node. Input: head = [1,2], pos = 0 Output: true Explanation: There is a cycle in the linked list, where tail connects to the first node. Input: head = [1], pos = -1 Output: false Explanation: There is no cycle in the linked list. Follow up: Can you solve it using O(1) (i.e. constant) memory?
思路:
先思考如何能判断出有环:
使用两个指针,一个快指针,一个慢指针——快指针一次移动两步、慢指针一次移动一步
如果一个链表中含有环,那么快指针和慢指针总会相遇(可画图看到,其相遇的步数为进入从链表开头到环入口的长度)
而如果链表中没有环,则快指针会先一步到达null,只需要判断在跳出循环时,是否有指针为null即可
代码:
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while(slow!=fast && slow!=null && fast!=null) {
slow = slow.next;
fast = fast.next;
if(fast!=null) {
fast = fast.next;
}
}
if(slow==null || fast==null) {
return false;
}else {
return true;
}
}
}