题目
给定一个链表,判断链表中是否有环。为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
解法:利用双指针(一快一慢),快指针每次走两步,慢指针每次走一步,若有环则快指针会追上慢指针,则返回true否则返回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) {
var pointer = head;
while(pointer!=null&&pointer.next!=null)
{
head = head.next;
pointer = pointer.next.next;
if(head == pointer)return true;
}
returm false;
}
}
结果:
执行用时 : 220 ms, 在Linked List Cycle的C#提交中击败了24.24% 的用户内存消耗 : 23.5 MB, 在Linked List Cycle的C#提交中击败了51.28% 的用户。