zoukankan      html  css  js  c++  java
  • LeetCode141 环形链表

    给定一个链表,判断链表中是否有环。

    为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

    快慢指针,一个走两步一个走一步,迟早相遇。注意判断长度为0或1的情况。

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     bool hasCycle(ListNode *head) {
    12         if(!head || !head->next)
    13             return false;
    14         ListNode* fast, *slow;
    15         fast=head;
    16         slow=head;
    17         while(fast!=nullptr){
    18             if(slow)
    19                 slow=slow->next;
    20             if(fast)
    21                 fast=fast->next;
    22             if(fast)
    23                 fast=fast->next;
    24             if(fast==slow && fast!=nullptr)
    25                 return true;
    26         }
    27         return false;
    28     }
    29 };
  • 相关阅读:
    Python-单例模式
    Django 内置模板标签和过滤器
    Python Built-in Function 学习笔记
    Django 中间件
    Django Form
    Ajax
    Django中cookie和session
    Django中的QuerySet
    Django模型和ORM
    wordpress添加子主题
  • 原文地址:https://www.cnblogs.com/rookiez/p/13393924.html
Copyright © 2011-2022 走看看