前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode-Easy 141. Linked List Cycle

Leetcode-Easy 141. Linked List Cycle

作者头像
致Great
发布2018-04-11 16:37:58
6230
发布2018-04-11 16:37:58
举报
文章被收录于专栏:程序生活程序生活

141. Linked List Cycle

  • 描述: 判断一个单链表中是否存在环
  • 思路: 设置两个指针(fast, slow),初始值都指向头,slow每次前进一步,fast每次前进二步,如果链表存在环,则fast必定先进入环,而slow后进入环,两个指针必定相遇。(当然,fast先行头到尾部为NULL,则为无环链表)
  • 代码
代码语言:javascript
复制
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:  
 
    def hasCycle(self, head):  
        # write your code here  
        if head is None:  
            return False  
        if head.next is None:  
            return False  
        slow = head.next  
        fast = head.next  
        if fast.next is not None:  
            fast = fast.next  
        while (slow.next is not None) and (fast.next is not None):  
            if slow == fast:  
                return True  
            slow = slow.next  
            fast = fast.next  
            if fast.next != None:  
                fast = fast.next  
        return False   
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.03.21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 141. Linked List Cycle
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档