题目
给定一个链表,判断链表中是否有环。
分析
通过使用具有 不同速度 的快、慢两个指针遍历链表,空间复杂度可以被降低至 O(1)O(1)。慢指针每次移动一步,而快指针每次移动两步。
如果列表中不存在环,最终快指针将会最先到达尾部,此时我们可以返回 false。
C
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
if(head==NULL||head->next == NULL)
return false;
struct ListNode *s,*f;
s = head;
f = head->next;
while(s != f)
{
if(f==NULL||f->next==NULL)
return false;
s = s->next;
f = f->next->next;
}
return true;
}
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 fast and fast.next:
fast = fast.next.next
slow = slow.next
if slow == fast:
return True
return False
总结
环形链表问题
https://blog.csdn.net/qq_34364995/article/details/80518191