定義快慢兩個指針,慢指針每次前進一步,快指針每次前進兩步,若鏈表有環,則快慢指針必定會相遇。node
/** * 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;
}
};
複製代碼
用 unordered_map 充當散列表的功能,每次將鏈表的節點指針做爲鍵值存入 map,若是檢測到當前節點指針已經存在於 map 中則說明鏈表有環。ui
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」! spa