1. 程式人生 > 其它 >牛客網 | 高頻面試題 | 判斷連結串列中是否有環

牛客網 | 高頻面試題 | 判斷連結串列中是否有環

技術標籤:刷題# 牛客連結串列leetcode單鏈表

文章目錄

題目

題目描述
判斷給定的連結串列中是否有環。如果有環則返回true,否則返回false。
你能給出空間複雜度的解法麼?

題解

快慢指標

/**
 * 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||head->next==nullptr)return false; ListNode *slow=head,*fast=head->next; //連結串列多長? while(slow!=fast){ if(fast==nullptr||slow==nullptr||fast->next==nullptr)return false; slow=slow->
next; fast=fast->next->next; } return true; } };

雜湊表

/**
 * 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) { set<ListNode*> hash_map; ListNode *p=head; while(p!=nullptr){ if(hash_map.count(p)){ return true; } hash_map.insert(p); p=p->next; } return false; } };