Leetcode快慢指针寻找环形链表(一)

题目

1.给定一个链表,判断链表中是否有环。
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
PS:从例子中根本看不出来好嘛。。。。。。自己理解就ok
思路
经典思想,快慢指针,如果有环存在,快指针总会追上慢指针
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 not head:
            return False
        first=head
        second=head
        while True:
            if first.next is None or first.next.next is None:
                return False
            first=first.next.next   # 快指针,二倍速
            second=second.next      # 慢指针 ,一倍速
            if first==second:
                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)
    {
        ListNode *low = head;  // 指针指向头部的语句
        ListNode *high = head;
        if(head==NULL)
            return 0;
        while((high!=NULL) && (high->next!=NULL))  // 且运算符
        {
            low=low->next;   // 在c++中  -> 就是指针中的.
            high = high->next->next;
            if(low==high)
                return 1;
        }
        return 0;
            
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_44433306/article/details/87932165