题目:
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:
输入:head = [1,2], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。
示例 3:
输入:head = [1], pos = -1
输出:false
解释:链表中没有环。
链接:https://leetcode-cn.com/problems/linked-list-cycle
思路:
1、使用快慢双指针,快指针每次走两步,慢指针每次走一步。遍历上述流程,如果 快指针走到了None,则说明没有环。如果快指针和慢指针一样,则说明有环
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:
return False
fast = head.next
slow = head
while (fast!=slow):
if (fast == None or fast.next == None or fast.next.next == None):
return False
fast = fast.next.next
slow = slow.next
return True
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) {
if (head == nullptr) {
return false;
}
ListNode* fast = head->next;
ListNode* slow = head;
while(fast!=slow){
if(fast==nullptr || fast->next==nullptr || fast->next->next==nullptr){
return false;
}
fast = fast->next->next;
slow = slow->next;
}
return true;
}
};