博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] 141. Linked List Cycle 链表中的环
阅读量:4607 次
发布时间:2019-06-09

本文共 1235 字,大约阅读时间需要 4 分钟。

Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

给定一个链表,判断是否有环存在。Follow up: 不使用额外空间。

解法:双指针,一个慢指针每次走1步,一个快指针每次走2步的,如果有环的话,两个指针肯定会相遇。

Java:

public class Solution {    public boolean hasCycle(ListNode head) {        ListNode slow = head, fast = head;        while (fast != null && fast.next != null) {            slow = slow.next;            fast = fast.next.next;            if (slow == fast) return true;        }        return false;    }}

Python:

class ListNode:    def __init__(self, x):        self.val = x        self.next = Noneclass Solution:    # @param head, a ListNode    # @return a boolean    def hasCycle(self, head):        fast, slow = head, head        while fast and fast.next:            fast, slow = fast.next.next, slow.next            if fast is slow:                return True        return False  

C++:

class Solution {public:    bool hasCycle(ListNode *head) {        ListNode *slow = head, *fast = head;        while (fast && fast->next) {            slow = slow->next;            fast = fast->next->next;            if (slow == fast) return true;        }        return false;    }};

  

类似题目:

 

 

转载于:https://www.cnblogs.com/lightwindy/p/8607015.html

你可能感兴趣的文章
33. Search in Rotated Sorted Array
查看>>
461. Hamming Distance
查看>>
Python垃圾回收机制详解
查看>>
jquery 编程的最佳实践
查看>>
MeetMe
查看>>
IP报文格式及各字段意义
查看>>
(转载)rabbitmq与springboot的安装与集成
查看>>
C2. Power Transmission (Hard Edition)(线段相交)
查看>>
STM32F0使用LL库实现SHT70通讯
查看>>
Atitit. Xss 漏洞的原理and应用xss木马
查看>>
MySQL源码 数据结构array
查看>>
(文件过多时)删除目录下全部文件
查看>>
T-SQL函数总结
查看>>
python 序列:列表
查看>>
web移动端
查看>>
pythonchallenge闯关 第13题
查看>>
linux上很方便的上传下载文件工具rz和sz使用介绍
查看>>
React之特点及常见用法
查看>>
【WEB前端经验之谈】时间一年半,或沉淀、或从零开始。
查看>>
优云软件助阵GOPS·2017全球运维大会北京站
查看>>