鏈表 | 環形鏈表

問題:環形鏈表


![在這裏插入圖片描述](https://img-blog.csdnimg.cn/20200306202857493.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1NvbmdCYWkxOTk3,size_16,color_FFFFFF,t_70在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

解題思路

使用集合set存放已經出現的節點,如果在遍歷結束之前訪問了set中已經有的節點,說明有環,否則沒有環。

C++代碼

/**
 * 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*> s;
        while(head){
            if(s.find(head) != s.end()) return true;
            s.insert(head);
            head = head->next;
        }
        return false;
    }
};

問題:環形鏈表 II

問題鏈接
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

解題思路

使用集合set存放已經出現的節點,如果在遍歷結束之前訪問了set中已經有的節點,說明有環,且第一個是入環的節點,否則沒有環。

C++代碼

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        set<ListNode*>s;
        while(head){
            if(s.find(head) != s.end())//如果此節點已經被訪問
                return head;
            else
                s.insert(head);//將訪問過的節點插入集合中
            head = head->next;
        }
        return NULL;//沒有環,返回NULL
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章