141. Linked List Cycle

Posted lychnis

tags:

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

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

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

 

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.

技术图片

Example 2:

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.

技术图片

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

技术图片

 

Follow up:

Can you solve it using O(1) (i.e. constant) memory?

 

 

链表判断环问题, 传统解法把链表节点全部保存下来, 然后遍历看下一个节点是否已经保存过了. 时间复杂度O(N). 空间复杂度O(N).

如果不想用空间, 则用两个指针,一个走两步,一个走一步,有环的时候他们一定相遇. 时间复杂度比较随机, 但小于O(N).

例如链表的环外长度为6, 环的长度为10. 则一共需要走10步他们就能相遇. 链表总长度16

分析: 假设走N步, 那么相遇的时候快指针一定比慢指针多走一圈

2N - N = 环长度.  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(NULL==head)
            return false;
        ListNode *fast=head, *low=head;
        while(fast->next&&fast->next->next)
        {
            low=low->next;
            fast=fast->next->next;
            if(fast==low)return true;
        }
        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