给定一个链表,判断链表中是否有环。
设置两个指针,一个fast一个slow,遍历整个列表,若达到表尾时仍未出现指针相等则链表无环。
C语言版:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
struct ListNode *fast, *slow;
if(head == NULL || head -> next == NULL)
return false;
slow = head;
fast = head -> next;
while(slow != fast){
if(fast == NULL || fast -> next == NULL)
return false;
slow = slow -> next;
fast = fast -> 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
"""
if head == None or head.next == None:
return False
slow = head
fast = head.next
while fast != slow:
if fast == None or fast.next == None:
return False
slow = slow.next
fast = fast.next.next
return True

本文介绍了一种高效的链表有环检测算法,通过使用快慢指针遍历链表,判断链表是否存在环。提供了C语言和Python两种实现方式,适用于链表数据结构的学习与实践。
639

被折叠的 条评论
为什么被折叠?



