zoukankan      html  css  js  c++  java
  • leetcode 141

    141. 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         ListNode * slow = head;
    13         ListNode * fast = head;
    14         while(fast != NULL && fast->next != NULL )
    15         {
    16             fast = fast->next->next;
    17             slow = slow->next;
    18             if(fast == slow)
    19             {
    20                 return true;
    21             }
    22         }
    23         return false;
    24     }
    25 };
  • 相关阅读:
    数据快照
    2.21毕设进度
    2.20毕设进度
    Java读取文件,明明文件存在,却报错文件找不到
    2.19毕设进度
    2.18毕设进度
    2.17毕设进度
    2.16毕设进度
    2.15毕设进度
    2.14毕设进度
  • 原文地址:https://www.cnblogs.com/shellfishsplace/p/5947345.html
Copyright © 2011-2022 走看看