141一覧サイクルリンク*
https://leetcode.com/problems/linked-list-cycle/
タイトル説明
それはそれでサイクルを持っている場合、リンクされたリストを考えると、決定します。
与えられたリンクされたリストにサイクルを表すために、我々は整数使用pos
尾に接続するリンクされたリスト内の位置(0インデックス)を表します。場合pos
で-1
は、リンクされたリストにはサイクルがありません。
例1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.
例2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.
例3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
ファローアップ:
あなたは使用してそれを解決することができます (すなわち一定の)メモリ?
C ++の実装1
リングの速度か否かを決定するためにポインタを使用して、最初の初期化中に書かれた、速度ポインタが同じノードを指していません。
さらに、142サイクルII **リンクリストこの問題は、リングの開始ノードを見つけることが必要です。
class Solution {
public:
bool hasCycle(ListNode *head) {
if (!head || !head->next) return false;
ListNode *slow = head, *fast = head->next;
while (fast && fast->next && slow != fast) {
slow = slow->next;
fast = fast->next->next;
}
return slow == fast;
}
};
C ++での2
そのようなアプローチは、同じノードポインタ速度を初期点です。
class Solution {
public:
bool hasCycle(ListNode *head) {
if (!head || !head->next)
return false;
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (fast == slow)
return true;
}
return false;
}
};