给定一个链表,判断链表中是否有环。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:
输入:head = [1,2], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。
示例 3:
输入:head = [1], pos = -1
输出:false
解释:链表中没有环。
提示:
链表中节点的数目范围是 [0, 104]
-105 <= Node.val <= 105
pos 为 -1 或者链表中的一个 有效索引 。
快慢指针
给定两个指针,一个快,一个慢,如果两个指针相遇,则说明有环
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode quickCur= head,manCur= head;
while (true){
if(quickCur==null||quickCur.next==null)return false;
quickCur = quickCur.next.next;
manCur = manCur.next;
if(quickCur==manCur){
return true;
}
}
}
}
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
fast = head
show = head
while True:
if fast==None or fast.next==None:
return False
fast = fast.next.next
show = show.next
if fast==show:
return True
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null
。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:返回索引为 1 的链表节点
解释:链表中有一个环,其尾部连接到第二个节点。
快慢指针
当两个指针第一次相遇以后, 把快指针重新指向头节点,
两个指针都变为每次移动一个位置,
当第二次相遇时, 该节点就是头节点
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode quickCur = head, showCur = head;
while (true) {
if (quickCur == null || quickCur.next == null) return null;
quickCur = quickCur.next.next;
showCur = showCur.next;
if (quickCur == showCur) break;
}
quickCur = head;
while (showCur != quickCur) {
showCur = showCur.next;
quickCur = quickCur.next;
}
return quickCur;
}
}
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
fast = head
show = head
while True:
if fast==None or fast.next==None:
return None
fast = fast.next.next
show = show.next
if fast == show:
break
fast = head
while fast!=show:
fast = fast.next
show = show.next
return fast