力扣学习笔记:141. 环形链表

题目:https://leetcode-cn.com/problems/linked-list-cycle/
算法
哈希表

  1. 首先用指针遍历链表
  2. 并用哈希表保存遍历时遇到的结点,如果下次遇到,就说明这个链表具有环

快慢指针

  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) {
    
    
        if(head == nullptr){
    
    
            return false;
        }
        ListNode* fast;
        ListNode* low;

        fast = head;
        low = head;

        while(fast != nullptr && fast->next != nullptr && low != nullptr){
    
    
            fast = fast->next->next;
            low = low->next;
            if(fast == low){
    
    
                return true;
            }
        }
        return false;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_45914759/article/details/109138672