zoukankan      html  css  js  c++  java
  • 【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;
        }
    };

  • 相关阅读:
    JDBC的简单笔记
    javascript学习笔记二
    javascript学习一、js的初步了解
    css的简单学习笔记
    c++ 拷贝构造函数
    C++ new delete
    c++ 析构函数
    c++成员初始化和构造函数
    C++ 类和对象浅解
    c++ constexpr
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/3728818.html
Copyright © 2011-2022 走看看