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 };
  • 相关阅读:
    数组操作
    HTML CSS 笔记
    jacascript 滚动scroll
    SEO优化技巧
    STP选举规则和例题
    3.1GSM-R的网络组成
    光缆的型号
    光缆的种类
    fdisk命令分区过程
    文件系统管理--挂载光盘与U盘
  • 原文地址:https://www.cnblogs.com/shellfishsplace/p/5947345.html
Copyright © 2011-2022 走看看