[Leetcode] 141. Linked List Cycle 解题报告

来源:互联网 发布:mysql重置root密码 编辑:程序博客网 时间:2024/04/29 20:25

题目

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

思路

这个题目估计已经被问烂了,玩坏了。所以真正面试的时候估计一般不会考。不过里面two pointers的思路倒是解决链表问题的神器之一。我们定义快慢指针,慢的一次走一步,快的一次走两步。如果相遇,则有环,否则无环。时间复杂度O(n),空间复杂度O(1),其中n是链表的长度。

代码

/** * 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) {            return false;        }        ListNode *slow = head, *fast = head;        while (fast->next && fast->next->next) {            slow = slow->next;            fast = fast->next->next;            if (slow == fast) {                return true;            }        }        return false;    }};

0 0
原创粉丝点击