一、题目内容

image.png

二、题解

解法1:

思路

快慢指针,假如有环,最终快慢指针都会进入环内,每一次移动,快指针与慢指针的距离都会-1,最终一定会相遇

代码

  1. public class Solution {
  2. public boolean hasCycle(ListNode head) {
  3. if(head == null || head.next == null){
  4. return false;
  5. }
  6. ListNode fast = head;
  7. ListNode slow = head;
  8. while(fast!=null&&fast.next!=null){
  9. fast = fast.next.next;
  10. slow = slow.next;
  11. if(fast == slow){
  12. return true;
  13. }
  14. }
  15. return false;
  16. }
  17. }

解法2:

思路

挨个删除,针对每一个节点,head=head.next
如果没有环,那最后,一定会有一个节点head,head.next=null
如果有换,那最后的节点,一定是之前已经删过的节点,即存在head=head.next

代码

  1. public class Solution {
  2. public boolean hasCycle(ListNode head) {
  3. if(head == null || head.next == null){
  4. return false;
  5. }
  6. if(head.next == head){
  7. return true;
  8. }
  9. ListNode next = head.next;
  10. head.next = head;
  11. return hasCycle(next);
  12. }
  13. }