1. 程式人生 > >LeetCode 141——環形連結串列

LeetCode 141——環形連結串列

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」!