zoukankan      html  css  js  c++  java
  • LeetCode——linked-list-cycle

    Question

    Given a linked list, determine if it has a cycle in it.
    Follow up:
    Can you solve it without using extra space?

    Solution

    判断一个链表是否有环,可以采用slow-fast的方法,也就是两个指针,一个指针一次性只走一步,一个指针一次性走两步,如果有环的话,他们毕定相遇,如果没有的话,fast肯定会走到空的。

    Code

    class Solution {
    public:
        bool hasCycle(ListNode *head) {
            if (head == NULL)
                return false;
            
            ListNode* slow = head;
            ListNode* fast = head;
            
            while (1) {
                slow = slow->next;
                // 因为fast走的比slow快,所以只需要判断fast就好了
                if (fast->next != NULL && fast->next->next != NULL) {
                    fast = fast->next->next;
                } else
                    return false;
                if (slow == fast)
                    return true;
            }
        }
    };
    
  • 相关阅读:
    socketserver模块
    socketserver密文测试
    Less11-Less12
    Less-5-03
    google语法
    Nmap
    01真的很简单
    kali linux 安装后的必要修改
    SQLMap-02
    SQLMap-01
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7077051.html
Copyright © 2011-2022 走看看