Leetcode-Easy 141. Linked List Cycle

简介: Leetcode-Easy 141. Linked List Cycle

141. Linked List Cycle


  • 描述:
    判断一个单链表中是否存在环2.png
  • 思路:
    设置两个指针(fast, slow),初始值都指向头,slow每次前进一步,fast每次前进二步,如果链表存在环,则fast必定先进入环,而slow后进入环,两个指针必定相遇。(当然,fast先行头到尾部为NULL,则为无环链表)


  • 代码

# 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


相关文章
|
6月前
|
Java
Leetcode 114. Flatten Binary Tree to Linked List
思路也很简单,先把root的左子树(如有)变成单链表 leftlinkedlist,把root的右子树(如有)变成单链表 rightlinkedlist,再把root的右节点变成leftlikedlist,再把rightlinkedlist接到leftlinkedlist后面,代码如下。
20 1
|
6月前
|
C++
Leetcode Copy List with Random Pointer(面试题推荐)
给大家推荐一道leetcode上的面试题,这道题的具体讲解在《剑指offer》的P149页有思路讲解,如果你手头有这本书,建议翻阅。
27 0
|
6月前
Leetcode 19.Remove Nth Node From End of List
删除单链表中的倒数第n个节点,链表中删除节点很简单,但这道题你得先知道要删除哪个节点。在我的解法中,我先采用计数的方式来确定删除第几个节点。另外我在头节点之前额外加了一个节点,这样是为了把删除头节点的特殊情况转换为一般情况,代码如下。
20 0
|
5月前
|
大数据 Java 程序员
「LeetCode合集」链表(List)及经典问题
「LeetCode合集」链表(List)及经典问题
27 0
LeetCode 141. 环形链表 Linked List Cycle
LeetCode 141. 环形链表 Linked List Cycle
LeetCode 234. 回文链表 Palindrome Linked List
LeetCode 234. 回文链表 Palindrome Linked List
LeetCode 206. 反转链表 Reverse Linked List
LeetCode 206. 反转链表 Reverse Linked List
LeetCode 19. 删除链表的倒数第N个节点 Remove Nth Node From End of List
LeetCode 19. 删除链表的倒数第N个节点 Remove Nth Node From End of List
LeetCode 237. 删除链表中的节点 Delete Node in a Linked List
LeetCode 237. 删除链表中的节点 Delete Node in a Linked List
LeetCode Contest 178-1367. 二叉树中的列表 Linked List in Binary Tree
LeetCode Contest 178-1367. 二叉树中的列表 Linked List in Binary Tree

热门文章

最新文章