zoukankan      html  css  js  c++  java
  • leetcode 10: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?
    题目分析:
    此题为常规题,使用快慢指针来判断链表中是否有环,慢指针每次走一步,快指针每次走两步,当快慢指针指向一个节点时则判断链表有环。
    代码如下:
     1 bool hasCycle(ListNode *head) {
     2         if(head == NULL)
     3             return false;
     4         ListNode* slow = head;
     5         ListNode* fast = head;
     6         while(fast->next != NULL && fast->next->next != NULL){
     7             slow = slow->next;
     8             fast = fast->next->next;
     9             if(fast == slow)
    10                 return true;
    11         }
    12         return false;
    13     }
     
     
     
  • 相关阅读:
    BZOJ 1088 模拟(扫雷经验…)
    BZOJ 1529
    BZOJ 3224
    BZOJ 1192
    BZOJ 1012
    博客搬家说明
    BZOJ 2423 DP
    BZOJ 1789&1830 推式子 乱搞
    BZOJ 1588
    拆点:虫洞
  • 原文地址:https://www.cnblogs.com/qingjiaowoxiaoxioashou/p/13453355.html
Copyright © 2011-2022 走看看