zoukankan      html  css  js  c++  java
  • 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?

    分析:这道题限制条件是不可以用额外空间,然而我们就不能需求用栈或队列来求解了。我们换一种思路,使用两个指针,一个是走的比较快一次走两步,另一个是走的比较慢一次走一步,如果快的指针追上慢指针说明有环,否则没有。

    C++代码:

    /**
     * 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(head==NULL||head->next==NULL)
                return false;
            ListNode* behind=head;
            ListNode* ahead=head->next;
            while(ahead->next!=NULL)
            {
                ahead=ahead->next;
                if(ahead==NULL)
                    return false;
                if(behind==ahead)
                    return true;
                ahead=ahead->next;
                if(ahead==NULL)
                    return false;
                if(ahead==behind)
                    return true;
                behind=behind->next;
                if(behind==ahead)
                    return true;
            }
        }
    };
  • 相关阅读:
    ORACLE常用SQL优化hint语句
    TestNG 入门教程
    博客迁移
    WebMvcConfigurer
    Nginx 配置
    SpringBoot部署
    MyBatis 动态 SQL
    Spring Boot 验证表单
    Spring Boot session与cookie的使用
    Spirng MVC 重定向传递对象
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3577255.html
Copyright © 2011-2022 走看看