Skip to content

Instantly share code, notes, and snippets.

@unilecs
Created October 13, 2017 08:37
Show Gist options
  • Save unilecs/06fe6b9468e1e080f7720bc5ff0b79b7 to your computer and use it in GitHub Desktop.
Save unilecs/06fe6b9468e1e080f7720bc5ff0b79b7 to your computer and use it in GitHub Desktop.
Найти цикл в односвязном списке
class Node {
constructor(uniqueId, data) {
this.uniqueId = uniqueId;
this.data = data;
this.next = null;
}
}
function detectCycleWithHashMap(root) {
let hashMap = {};
// идем по списку и записываем каждый узел в hashMap
while (root !== null) {
// если встретили узел, ктр уже есть в hashMap, то мы нашли цикл
if (hashMap[root.uniqueId]) {
return true;
}
hashMap[root.uniqueId] = root;
root = root.next;
}
return false;
}
function detectCycleWithPointers(root) {
let slowPointer = root, fastPointer = root;
// запускаем два указателя с разным шагом
while (slowPointer !== null && fastPointer !== null && fastPointer.next !== null) {
slowPointer = slowPointer.next;
fastPointer = fastPointer.next.next;
// если указатели встретились в одном узле, то мы нашли цикл
if (fastPointer && slowPointer
&& slowPointer.uniqueId === fastPointer.uniqueId) {
return true;
}
}
return false;
}
let list = new Node(1, 1);
list.next = new Node(2, 2);
list.next.next = new Node(3, 2);
list.next.next.next = list.next;
console.info(detectCycleWithHashMap(list)); // true
console.info(detectCycleWithPointers(list)); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment