• [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 };
  • 相关阅读:
    生成8位随机字符串
    Python字符串反转
    dd备份文件系统
    多线程mtr-代码
    Sysctl命令及linux内核参数调整
    解决系统存在大量TIME_WAIT状态的连接
    tcpkill清除异常tcp连接
    graphite
    sed 中带变量的情况
    JAVA的Random类
  • 原文地址:https://www.cnblogs.com/love-yh/p/7018115.html
Copyright © 2020-2023  润新知