Day 8
题目:判断单链表是否包含环并找出环起点
leetcode链接:环形链表
leetcode链接:环形链表II
要点:双指针
一、判断链表是否包含环
1、Java
public class Solution {
public boolean hasCycle(ListNode head) {
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、python
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
fast = head
slow = head
while fast != None and fast.next != None:
fast = fast.next.next
slow = slow.next
if fast == slow:
return True
return False
二、判断单链表是否包含环并找出环起点
1、Java
public class Solution {
public ListNode detectCycle(ListNode head) {
// 先判断是否存在环
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow) break;
}
// fast遇到空指针说明没有环
if(fast == null || fast.next == null) return null;
// slow指针重新指向头节点
slow = head;
while(fast != slow){
// 快慢指针同步前进,相交点就是环起点
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
2、python
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
fast = head
slow = head
while fast != None and fast.next != None:
fast = fast.next.next
slow = slow.next
if fast == slow:
break
if fast == None or fast.next == None:
return None
slow = head
while fast != slow:
fast = fast.next
slow = slow.next
return slow