LeetCode算法题解 141-环形链表

题目描述

题解:

看代码。

代码:

/**
 * 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) {
        /* 方法1:置某个不会出现的数 O(1)的空间,但是不一定对
        if(head == NULL)
        {
            return false;
        }
        else
        {
            while(head)
            {
                if(head->val == INT_MAX)
                {
                    return true;
                }
                else
                {
                    head->val = INT_MAX;
                }
                head = head->next;
            }
            return false;
        }*/
        /* 方法2:记录下节点的内存地址 O(n) 
        set <ListNode* > node;
        while(head)
        {
            if(node.find(head) != node.end())
            {
                return true;
            }
            node.insert(head);
            head = head->next;
        }
        return false;*/
        /* 方法3:快慢指针法 
            如果链表没有环,low指针和fast指针一定不会相遇,
                1. 当fast==NULL(fast直接跳两次,到达了尾部+1的位置)
                2. 当fast->next==NULL(fast正好到达最后一个位置)
                遇到上述两种情况,退出循环返回false。
            如果有环,low和fast一定会相遇,
                返回true。
            注意:如果链表只有一个节点,是有可能有环的(自己指向自己),但是该节点的next指向空就是没有环
        */
        ListNode* fast;
        ListNode* low;
        fast = low = head;
        while(fast && fast->next)
        {
            low = low->next;
            fast = fast->next->next;
            if(low == fast)
            {
                return true;
            }
        }
        return false;

    }
};
发布了197 篇原创文章 · 获赞 18 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_41708792/article/details/104581139