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

    判断链表中是否有环,不能用额外的空间,可以使用快慢指针,慢指针一次走一步,快指针一次走两步,若是有环则快慢指针会相遇,若是fast->next==NULL则没有环。

    值得注意的是:在链表的题中,快慢指针的使用频率还是很高,值得注意。

     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     {
    13         ListNode *pFast=head;
    14         ListNode *pSlow=head;
    15 
    16         while(pFast&&pFast->next)
    17         {
    18             pSlow=pSlow->next;
    19             pFast=pFast->next->next;
    20             if(pFast==pSlow)
    21                 return true;
    22         }    
    23         return false;
    24     }
    25 };
  • 相关阅读:
    bugku 求getshell
    HTTP之content-type
    web之robots.txt
    HTTP之User-Agent大全
    bugku 细心
    PHP输入流
    bugku web8
    PHP中sha1()函数和md5()函数的绕过
    bugku 各种·绕过
    【学术篇】烧水问题 打表找规律做法
  • 原文地址:https://www.cnblogs.com/love-yh/p/7018115.html
Copyright © 2011-2022 走看看