zoukankan      html  css  js  c++  java
  • LeetCode OJ: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 class Solution {
     2 public:
     3     bool hasCycle(ListNode *head) {
     4         ListNode * slow, * fast;
     5         slow = fast = head;
     6         while(slow && fast){
     7             slow = slow->next;
     8             fast = fast->next;
     9             if(fast) fast = fast->next;
    10             if(fast && slow && slow == fast)
    11                 return true;
    12         }
    13         return false;
    14     }
    15 };
  • 相关阅读:
    JPA01
    mybatis入门
    PHP 循环- While循环
    PHP超级全局变量
    PHP 数组排序
    PHP数组
    PHP Switch语句
    PHP IF...Else语句
    PHP运算符
    PHP字符串变量
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4934642.html
Copyright © 2011-2022 走看看