1. 程式人生 > >LeetCode 141——環形鏈表

LeetCode 141——環形鏈表

gem 節點 har truct emp lse use https lis

1. 題目

技術分享圖片

2. 解答

2.1 方法 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) {
        
        ListNode *slow = head;
        ListNode *fast = head;
        
        while (fast && fast->next)
        {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) return true;
        }
         return false;
    }
};
2.2 方法 2

用 unordered_map 充當散列表的功能,每次將鏈表的節點指針作為鍵值存入 map,如果檢測到當前節點指針已經存在於 map 中則說明鏈表有環。

class Solution {
public:
    bool hasCycle(ListNode *head) {
        
        unordered_map<ListNode *, char> nodemap; // 散列表功能
        ListNode *temp = head;
        
        while (temp)
        {
            if (nodemap.count(temp) == 1) return true; // 當前節點已存在於 map 中,則說明有環
            nodemap[temp] = ‘0‘;
            temp = temp->next;
        }
        return false;
    }
};

獲取更多精彩,請關註「seniusen」!
技術分享圖片

LeetCode 141——環形鏈表