141. Linked List Cycle

Posted 小河沟大河沟

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了141. Linked List Cycle相关的知识,希望对你有一定的参考价值。

欢迎fork and star:Nowcoder-Repository-github

141. Linked List Cycle

题目

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

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

解答

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
// Linked List Cycle
class Solution{
public:
    bool hasCycle(ListNode *head) {
        if (!head||!head->next)
        {
            return false;
        }
        ListNode* slow=head;
        ListNode* fast = head->next;

        while (fast!=NULL&&fast->next!=NULL)
        {
            if (slow==fast)
            {
                return true;
            }

            slow = slow->next;
            fast = fast->next->next;
            
        }
        return false;
    }
};

题目来源

以上是关于141. Linked List Cycle的主要内容,如果未能解决你的问题,请参考以下文章

141. Linked List Cycle

141. Linked List Cycle

141. Linked List Cycle

141. Linked List Cycle

算法分析如何理解快慢指针?判断linked list中是否有环找到环的起始节点位置。以Leetcode 141. Linked List Cycle, 142. Linked List Cycl(代码

141. Linked List Cycle