• 【LeetCode】141. Linked List Cycle (2 solutions)


    Linked List Cycle

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

    Follow up:
    Can you solve it without using extra space?

    解法一:

    使用unordered_map记录当前节点是否被访问过,如访问过说明有环,如到达尾部说明无环。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        bool hasCycle(ListNode *head) {
            unordered_map<ListNode*, bool> visited;
            while(head != NULL)
            {
                if(visited[head] == true)
                    return true;
                visited[head] = true;
                head = head->next;
            }
            return false;
        }
    };

    解法二:不使用额外空间

    设置快慢指针,

    fast每次前进两步,slow每次前进一步,如相遇说明有环,如到达尾部说明无环。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        bool hasCycle(ListNode *head) {
            ListNode* fast = head;
            ListNode* slow = head;
            do
            {
                if(fast != NULL)
                    fast = fast->next;
                else
                    return false;
                if(fast != NULL)
                    fast = fast->next;
                else
                    return false;
                slow = slow->next;
            }while(fast != slow);
            return true;
        }
    };

  • 相关阅读:
    Mybatis plus 配置
    logback配置
    iview-ui-project-4.0 安装与配置
    Linux系统下Redis安装与配置
    Java中枚举的用法
    Mysql 查询所有课程的成绩第2名到第3名的学生信息及该课程成绩
    java 基础知识一 初识java
    docker 查看 挂载目录
    sqlserver统计所有表及表中记录数
    centos7配置禁用ipv6
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/3728818.html
Copyright © 2020-2023  润新知