判断给定的链表中是否有环:
如果有环则返回true,否则返回false。你能给出O(1)空间复杂度的解法么?
思路:快慢指针法
public boolean hasCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(null != fast && null != fast.next){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
return true;
}
}
return false;
}
找出链表中环的入口节点:
对于一个给定的链表,返回环的入口节点,如果没有环,返回null
思路:快慢指针法,找是否有环,然后找是入口节点,你能给出不利用额外空间的解法么?
公司:猿辅导
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(null != fast && null != fast.next){
slow = slow.next;
fast = fast.next.next;
// 有环
if(slow == fast){
// slow节点从头开始。
slow = head;
// 当slow和fast又相遇时,就是入口节点
while(slow != fast){
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
return null;
}