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?

     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==NULL)
    13                 return false;
    14             ListNode *p=head,*q;
    15             int n=0,m;
    16             while(p!=NULL)
    17             {
    18                 q=head;
    19                 m=0;
    20                 while(m<=n)
    21                 {
    22                     if(q==p->next)
    23                         return true;
    24                     else
    25                     {
    26                         q=q->next;
    27                         m++;
    28                     }
    29                 }
    30                 p=p->next;
    31                 n++;
    32             }
    33             return false;
    34         }
    35 };

    后记:在做Linked List Cycle II 的时候,发现上述解法效率太低,所以换了种思路:

    (1)定义slow和fast指针,都指向head结点,然后slow指针每次向后走1个结点,fast指针每次向后走2个结点。

    (2)如果fast指针为空,则说明不存在环;如果fast指针和slow指针相等,则说明存在环。

     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==NULL||head->next==NULL)
    13                 return false;
    14             ListNode *slow=head,*fast=head;
    15             while(fast!=NULL)
    16             {
    17                 slow=slow->next;
    18                 fast=fast->next;
    19                 if(fast!=NULL)
    20                     fast=fast->next;
    21                 if(slow==fast)
    22                     return true;
    23             }
    24             return false;
    25         }
    26 };
  • 相关阅读:
    测试用户网速办法
    JS 判断后端返回的对象是否为空
    优美地低于生活——读书笔记
    vue login.js登录逻辑
    vuex store index.js配置登录
    vue router的 index.js设置
    css 添加校验时的必填项前面的红色的*
    vue 的 main.js 设置
    vue.config.js配置
    vim的使用
  • 原文地址:https://www.cnblogs.com/levicode/p/3967313.html
Copyright © 2011-2022 走看看