一、题目内容
二、题解
解法1:
思路
快慢指针,假如有环,最终快慢指针都会进入环内,每一次移动,快指针与慢指针的距离都会-1,最终一定会相遇
代码
public class Solution {public boolean hasCycle(ListNode head) {if(head == null || head.next == null){return false;}ListNode fast = head;ListNode slow = head;while(fast!=null&&fast.next!=null){fast = fast.next.next;slow = slow.next;if(fast == slow){return true;}}return false;}}
解法2:
思路
挨个删除,针对每一个节点,head=head.next
如果没有环,那最后,一定会有一个节点head,head.next=null
如果有换,那最后的节点,一定是之前已经删过的节点,即存在head=head.next
代码
public class Solution {public boolean hasCycle(ListNode head) {if(head == null || head.next == null){return false;}if(head.next == head){return true;}ListNode next = head.next;head.next = head;return hasCycle(next);}}
