给定一个链表,判断链表中是否有环。
设置两个指针,一个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