给定一个链表,判断链表中是否有环。为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
方法1:哈希表
遍历链表的同时,将节点元素存入哈希表中,若在循环过程中出现了重复的节点,则证明含有环,返回true,若指针指到null,说明链表里没有环,返回false
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public bool HasCycle(ListNode head)
{
HashSet<ListNode> Hset=new HashSet<ListNode>();
Hset.Add(head);
while(head!=null)
{
head=head.next;
if(head==null)
return false;
if(Hset.Contains(head))
return true;
Hset.Add(head);
}
return false;
}
}
时间复杂度:O(n) 空间复杂度:O(n)
方法2:双指针法
使用一快一慢两个指针,快指针一次向后两个节点,慢指针一次向后一个节点。若链表内不含有环,则快指针会先指到null,返回false,若链表内含有环,则两个指针一定会相遇,当两个指针相遇时返回true。
public class Solution {
public bool HasCycle(ListNode head)
{
ListNode slow=head;
ListNode fast=head;
while(fast!=null&&fast.next!=null)
{
fast=fast.next.next;
slow=slow.next;
if(fast==slow)
{
return true;
}
}
return false;
}
}
时间复杂度:O(n) 空间复杂度:O(1)
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。