题目
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
c#
法一:
/**
* 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) {
ListNode p1=head;
ListNode p2=head;
while(p1!=null&&p1.next!=null)
{
p1=p1.next.next;
p2=p2.next;
if(p1==p2)
return true;
}
return 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> hash=new HashSet<ListNode>();
ListNode temp=head;
while(temp!=null)
{
if(hash.Contains(temp))
{
return true;
}
hash.Add(temp);
temp=temp.next;
}
return false;
}
}