zoukankan      html  css  js  c++  java
  • LeetCode 141——环形链表

    1. 题目

    2. 解答

    2.1 方法 1

    定义快慢两个指针,慢指针每次前进一步,快指针每次前进两步,若链表有环,则快慢指针一定会相遇。

    /**
     * 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 *slow = head;
            ListNode *fast = head;
            
            while (fast && fast->next)
            {
                slow = slow->next;
                fast = fast->next->next;
                if (slow == fast) return true;
            }
             return false;
        }
    };
    
    2.2 方法 2

    用 unordered_map 充当散列表的功能,每次将链表的节点指针作为键值存入 map,如果检测到当前节点指针已经存在于 map 中则说明链表有环。

    class Solution {
    public:
        bool hasCycle(ListNode *head) {
            
            unordered_map<ListNode *, char> nodemap; // 散列表功能
            ListNode *temp = head;
            
            while (temp)
            {
                if (nodemap.count(temp) == 1) return true; // 当前节点已存在于 map 中,则说明有环
                nodemap[temp] = '0';
                temp = temp->next;
            }
            return false;
        }
    };
    

    获取更多精彩,请关注「seniusen」!

  • 相关阅读:
    webpack初识
    Vue+ElementUi项目实现表格-单行拖拽
    promise/async与await 的执行顺序梳理
    MDN社区
    angularjs中的异步操作
    javascript中的字符串和数组的互转
    angularjs的练习题
    angularjs基础知识
    开发的两种方式
    ASP.NET中的HttpClient发送请求
  • 原文地址:https://www.cnblogs.com/seniusen/p/10142918.html
Copyright © 2011-2022 走看看