栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

leetcode刷题系列----模式1(Two Points 双指针)- 141:Linked List Cycle环形链表

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

leetcode刷题系列----模式1(Two Points 双指针)- 141:Linked List Cycle环形链表

Tips
  • Java和C#核心代码完全一样。
  • 这题比较简单,类似于时针和分针何时相遇。
  • 注意算法与数据结构的定义高度绑定,一定参照如何定义链表来思考解决此类问题的算法。
Python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        if not head or not head.next:
            return False
        
        fast = low = head
        while fast:
            fast = fast.next
            if fast:
                fast=fast.next
            low = low.next
            if fast == low:
                return True
        return False
C++
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head==nullptr || head->next==nullptr) return false;
        
        ListNode* fast = head;
        ListNode* low = head;
        while(fast!=nullptr)
        {
            fast = fast->next;
            if(fast==low) return true;
            
            if(fast!=nullptr) fast=fast->next;
            low = low->next;
            
        }
        return false;
    }
};
C#
public class Solution {
    public bool HasCycle(ListNode head) {
        if(head==null || head.next==null) return false;
        ListNode slow = head;
        ListNode fast = head;
        while(fast!=null)
        {
            fast = fast.next;
            if(fast!=null) fast = fast.next;
            if(slow==fast) return true;
            slow = slow.next;
        }
        return false;
    }
}
Java
public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head==null || head.next==null) return false;
        ListNode slow = head;
        ListNode fast = head;
        while(fast!=null)
        {
            fast = fast.next;
            if(fast!=null) fast = fast.next;
            if(slow==fast) return true;
            slow = slow.next;
        }
        return false;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/664510.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号