Leetcode-141. Linked List Cycle

来源:互联网 发布:2k18奥尼尔捏脸数据 编辑:程序博客网 时间:2024/05/29 11:54

题目

Given a linked list, determine if it has a cycle in it.
Follow up: Can you solve it without using extra space?
判断链表中是否有环,不用额外存储空间

思路

最好的方法是时间复杂度O(n),空间复杂度O(1)的。设置两个指针,一个快一个慢,快的指针每次走两步,慢的指针每次走一步,如果快指针和慢指针相遇,则说明有环。

代码

class Solution {public:    bool hasCycle(ListNode *head) {        // 设置两个指针,一个快一个慢        ListNode *slow = head, *fast = head;        while (fast && fast->next) {            slow = slow->next;            fast = fast->next->next;            if (slow == fast) return true;        }        return false;    }};
0 0
原创粉丝点击