• 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;
        }
    };
  • 相关阅读:
    日期格式化
    堆栈
    编写自己的C头文件
    线性表(gcc实现)
    排序的稳定性
    git创建和合并分支
    当单选input框改变时触发
    css样式定义
    div块显示在一行
    redis数据结构(一)
  • 原文地址:https://www.cnblogs.com/lychnis/p/12034530.html
Copyright © 2020-2023  润新知