Tips
- Java和C#核心代码完全一样。
- 这题比较简单,类似于时针和分针何时相遇。
- 注意算法与数据结构的定义高度绑定,一定参照如何定义链表来思考解决此类问题的算法。
Python
# 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:
if not head or not head.next:
return False
fast = low = head
while fast:
fast = fast.next
if fast:
fast=fast.next
low = low.next
if fast == low:
return True
return False
C++
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==nullptr || head->next==nullptr) return false;
ListNode* fast = head;
ListNode* low = head;
while(fast!=nullptr)
{
fast = fast->next;
if(fast==low) return true;
if(fast!=nullptr) fast=fast->next;
low = low->next;
}
return false;
}
};
C#
public class Solution {
public bool HasCycle(ListNode head) {
if(head==null || head.next==null) return false;
ListNode slow = head;
ListNode fast = head;
while(fast!=null)
{
fast = fast.next;
if(fast!=null) fast = fast.next;
if(slow==fast) return true;
slow = slow.next;
}
return false;
}
}
Java
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null || head.next==null) return false;
ListNode slow = head;
ListNode fast = head;
while(fast!=null)
{
fast = fast.next;
if(fast!=null) fast = fast.next;
if(slow==fast) return true;
slow = slow.next;
}
return false;
}
}