给定一个链表,判断链表中是否有环。
C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode * pFast = head;
ListNode * pSlow = head;
while(pSlow && pFast && pFast->next)
{
pSlow = pSlow->next;
pFast = pFast->next->next;
if(pFast == pSlow)
return true;
}
return false;
}
};
python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
fast = slow = head
while slow and fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
后记注意链表在连接时的顺序,以及python同时赋值的特性