zoukankan      html  css  js  c++  java
  • leetCode-linkedListCycle判断链表是否有环

    题目

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

    分析

    判断链表是否有环,采用快慢指针,如果相遇则表示有环

    AC代码

    /**
     * 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 || !head->next){
                return false;
            }
            ListNode* slow = head;
            ListNode* fast = head->next;
            while(fast->next && fast->next->next && fast != slow){
                fast = fast->next->next;
                slow = slow->next;
            }
            return fast == slow;
        }
    };
    
    转载请保留原文链接及作者
    本文标题:
    文章作者: LepeCoder
    发布时间:
    原始链接:
  • 相关阅读:
    (九)分类展示上
    (八)用户退出
    (七)用户登陆
    opencord视频截图
    (六)电子邮件
    (五)密码加密
    (四)用户注册
    (三)首页处理
    this关键字在继承中的使用
    03.swoole学习笔记--web服务器
  • 原文地址:https://www.cnblogs.com/lepeCoder/p/leetCode-linkedListCycle.html
Copyright © 2011-2022 走看看