LeetCode -- Linked List cycle
本題描述:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
檢測鏈表中是否有環。
思路:
經典算法,使用快慢指針,快的一次走兩步,慢的一次走一步,如果有環它們一定會相遇。
實現代碼:
/**
* 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) {
if(head == null){
return false;
}
var p = head;
var q = head;
while(p != null && q != null && q.next != null){
var t = q;
p = p.next;
q = q.next.next;
if(ReferenceEquals(p,q)){
return true;
}
}
return false;
}
}