题目
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
分析
1 判断链表是否有环 way 1 快慢指针
way 2 每遍历一个结点都将这个结点指向本身,如果再次遍历到指向其本身的结点,那么必然是有环的
代码
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null) return false;
ListNode slow = head;
ListNode fast = head.next;
while (slow != null && fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast) return true;
}
return false;
}
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;
boolean isCycle = hasCycle(next);
return isCycle;
}