【LeetCode】141. 環形鏈表

代碼

方法1 hash表

class Solution {
public:
	bool hasCycle(ListNode* head) {
		//特判
		if (head == nullptr || head->next == nullptr) return false;
		unordered_map<ListNode*,int> list;
		ListNode* cur = head;
		while (cur)
		{
			if (list.find(cur) != list.end()) return true;
			list[cur]++;
			cur = cur->next;
		}
		return false;
	}
};

方法2 雙指針

class Solution {
public:
	bool hasCycle(ListNode* head) {
		//特判
		if (head == nullptr || head->next == nullptr) return false;
		ListNode *slow = head;//慢指針
		ListNode* fast = head->next;//快指針
		while (slow!=fast)
		{
			if (fast == nullptr || fast->next == nullptr) return false;//fast已走爲null或fast走一步已爲null
			slow = slow->next;
			fast = fast->next->next;
		}
		return true;
	}
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章