First, the subject description:
Given a list, the list is determined whether a ring.
To show the list given ring, we integer pos connected to the end of the list to represent the position of the list (index starts from 0). If pos is -1, the ring is not on this list.
Example 1:
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
Example 2:
输入:head = [1,2], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。
Example 3:
输入:head = [1], pos = -1
输出:false
解释:链表中没有环。
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/linked-list-cycle
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
Second, the subject of analysis:
Using speed pointers, slow down a step, moving twice fast, slow and fast coincidence indicates a cycloalkyl.
Third, Code Description:
/**
* 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) {
//slow和fast都指向head
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;
}
}