Linked List Cycle

来源:互联网 发布:淘宝专业打假 编辑:程序博客网 时间:2024/05/09 12:15

描述
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
原创粉丝点击