zoukankan      html  css  js  c++  java
  • leetcode 141、Linked list cycle

    一种方法是用set存储出现过的指针,重复出现时就是有环:

     1 class Solution {
     2 public:
     3     bool hasCycle(ListNode *head) {
     4         set<ListNode*> st;
     5         ListNode *p = head;
     6         while(p) {
     7             if (st.find(p) != st.end())
     8                 return true;
     9             st.insert(p);
    10             p = p->next;
    11         }
    12         return false;
    13     }
    14 };
    View Code

    另一种方法就是快慢指针,快指针一次走两步,慢指针一次走一步。无环时快指针会走向空指针,有环时快指针会赶上慢指针。

     1 class Solution {
     2 public:
     3     bool hasCycle(ListNode *head) {
     4        ListNode *fast, *slow;
     5         fast = slow = head;
     6         while (fast && fast->next) {
     7             slow = slow->next;
     8             fast = fast->next->next;
     9             if (fast == slow)
    10                 return true;
    11         }
    12         return false;
    13     }
    14 };
  • 相关阅读:
    Python-模块
    POJ 1631 nlogn求LIS
    POJ 1274 二分图匹配
    POJ 3661 DP
    POJ 3662 二分+Dijkstra
    POJ 3666 DP
    POJ 2373 单调队列优化DP
    祝自己生日快乐
    POJ 2385 DP
    POJ 3122 Pie 二分答案
  • 原文地址:https://www.cnblogs.com/lxc1910/p/10275393.html
Copyright © 2011-2022 走看看