链表算法之【判断链表中是否有环】
目录
LeetCode-141题
LeetCode-141题
给定一个链表的头节点,判断链表中是否存在环
class Solution {public boolean hasCycle(ListNode head) {// checkif (head == null || head.next == null)return false;// 定义两个指针,一个快指针[fast],一个慢指针[slow],并且它们开始都指向头节点ListNode fast = head;ListNode slow = head;// fast指针一次前进两个节点,slow指针一次前进一个节点while (fast.next != null && fast.next.next != null) {fast = fast.next.next;slow = slow.next;// 如果fast和slow能相遇,链表存在环if (fast == slow) {return true;}}// 不能相遇,则链表不存在环return false;}private static class ListNode {int val;ListNode next;public ListNode() {}public ListNode(int val) {this.val = val;}public ListNode(int val, ListNode next) {this.val = val;this.next = next;}}
}