zoukankan      html  css  js  c++  java
  • Leecode刷题之旅-C语言/python-141环形链表

    /*
     * @lc app=leetcode.cn id=141 lang=c
     *
     * [141] 环形链表
     *
     * https://leetcode-cn.com/problems/linked-list-cycle/description/
     *
     * algorithms
     * Easy (35.53%)
     * Total Accepted:    28.4K
     * Total Submissions: 79.4K
     * Testcase Example:  '[3,2,0,-4]
    1'
     *
     * 给定一个链表,判断链表中是否有环。
     * 
     * 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
     * 
     * 
     * 
     * 示例 1:
     * 
     * 输入:head = [3,2,0,-4], pos = 1
     * 输出:true
     * 解释:链表中有一个环,其尾部连接到第二个节点。
     * 
     * 
     * 
     * 
     * 示例 2:
     * 
     * 输入:head = [1,2], pos = 0
     * 输出:true
     * 解释:链表中有一个环,其尾部连接到第一个节点。
     * 
     * 
     * 
     * 
     * 示例 3:
     * 
     * 输入:head = [1], pos = -1
     * 输出:false
     * 解释:链表中没有环。
     * 
     * 
     * 
     * 
     * 
     * 
     * 进阶:
     * 
     * 你能用 O(1)(即,常量)内存解决此问题吗?
     * 
     */
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    bool hasCycle(struct ListNode *head) {
        struct ListNode *p = head,*q = head;
        if(p == NULL)
            return false;
        else
        {
            while(1)
            {
                if(p->next == NULL||p->next->next == NULL)
                    return false;
                q = q->next;
                p = p->next->next;
                if(p == q)
                    return true;
            }
        }
    }

    题目很好理解。思路也很明确,这里判断结点的下一个和节点的下一个的下一个是否能循环连接起来,就可以判断是否是环形链表。

    -----------------------------------------------------------------------------------------------------------------------------------------------------------------------

    python:

    class Solution(object):
        def hasCycle(self, head):
            """
            :type head: ListNode
            :rtype: bool
            """
            fast = slow = head
            while fast and fast.next:
                fast = fast.next.next
                slow = slow.next
                if slow == fast:
                    return True
            return False
  • 相关阅读:
    飞思卡尔硬件 调试总结
    芯片散热器
    (028)[技术资料]et99加密狗打开函数的一个小bug
    (027)[技术资料]业余制作Windows图标
    (026)[工具软件]剪切板管理:Ditto
    (025)[系统故障]XP下禁止将串口设备识别成鼠标(转)
    (024)[工具软件]截屏录屏软件FSCapture(转)
    (023) 关于51单片机的A5指令
    (022)[工具软件]图片浏览 JPEGView
    (021)VMWare副虚拟磁盘和子虚拟磁盘id不匹配
  • 原文地址:https://www.cnblogs.com/lixiaoyao123/p/10529591.html
Copyright © 2011-2022 走看看