链表有环

2019-07-23  本文已影响0人  warManHy
  1. 遍历链表,判断节点 p->next 为null, 就到了链表最后
  2. map,标记访问过节点,重复访问有环
class Solution{
public: 
  bool hasCycle(ListNode *head){
    unordered_map<ListNode*,bool>m;
    while(head){
      if(m.find(head) != m.end()) return true;
      m[head] = true;
      head = head->next;
    }
    return false;
  }
};
  1. 一快一慢俩个节点,一个快一个慢,只要相遇就是有环
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if (head == NULL){
            return false;
        }
        ListNode *fast = head;
        ListNode *slow = head;
        while ( fast != NULL && slow !=NULL && fast->next != NULL ){
            slow = slow->next;
            fast = fast->next->next;
            if (fast == slow){
                return true;
            }
        }
        return false;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读