题目描述
题目链接
给定一个链表,判断该链表是否有环
思路分析
定义两个指针去遍历链表,指针fast每次向后移动两个位置,指针slow每次向后移动一个位置。如果快指针追上了慢指针,意味着该链表有环,否则,该链表不具有环
代码实现
/**
* 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) {
return false;
} else {
ListNode slow = head; //慢指针
ListNode fast = head; //快指针
while (fast != null && fast.next != null) {
slow = slow.next; //慢指针每次往后移动一个位置
fast = fast.next.next; //快指针每次往后移动两个位置
if (slow == fast) { //当快指针追上慢指针的时候,也就意味着该链表有环
return true;
}
}
return false;
}
}
}