2.算法-判断一个链表是否有环
2020-05-18 本文已影响0人
洧中苇_4187
给定一个链表,判断链表中是否有环: https://leetcode-cn.com/problems/linked-list-cycle/submissions/
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。

来源:力扣(LeetCode)
思路:使用快慢指针
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null) return false; 少于两个节点,直接返回false
ListNode fast = head.next;快指针
ListNode slow = head; 慢指针
while(fast != slow ){ 循环条件 快慢指针不相遇
if(fast == null || fast.next == null) return false; 快指针出现null,证明到了节点末尾,则没有环
fast = fast.next.next; 快指针走两步
slow = slow.next; 慢指针走一步
}
return true; 快慢指针相遇,有环
}
}