Problem Description
Determine whether there is a ring in the given linked list. If there is a loop, it returns true, otherwise it returns false.
Input description:
Input a linked list
Output description:
Does the output linked list contain rings?
Example
Example 1
Enter
1->2->3
Output
false
Solutions
analysis
- By means of fast and slow pointers, one pointer passes one node at a time, and the other pointer passes two nodes at a time. When the fast node catches up to full nodes, it means that it contains a ring structure.
method
- Judge by means of fast and slow pointers (tortoise and hare race: the picture uses the picture of the force button)
Code
// 思路1
public class Solution {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (fast != null && fast.next != null) {
if (fast == slow) {
return true;
}
slow = slow.next;
fast = fast.next.next;
}
return false;
}
If you want to test, you can go directly to the link of Niuke.com to do the test