Skip to content

Commit d9098e0

Browse files
committed
🔥 Linked List Cycle
1 parent f63dbf1 commit d9098e0

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,4 @@ Solutions of LeetCode Blind 75 Problems in JavaScript
3030
| [Longest Consecutive Sequence](./longest-consecutive-sequence.js) | <img src="https://img.shields.io/badge/-Medium-orange" /> | `Array`, `HashTable` | [:link:](https://leetcode.com/problems/longest-consecutive-sequence/) |
3131
| [Insert Interval](./insert-interval.js) | <img src="https://img.shields.io/badge/-Medium-orange" /> | `Array` | [:link:](https://leetcode.com/problems/insert-interval/) |
3232
| [Reverse Linked List](./reverse-linked-list.js) | <img src="https://img.shields.io/badge/-Easy-green" /> | `Linked List` | [:link:](https://leetcode.com/problems/reverse-linked-list/) |
33+
| [Linked List Cycle](./linked-list-cycle.js) | <img src="https://img.shields.io/badge/-Easy-green" /> | `Linked List`, `Hash Table`, `Two Pointers` | [:link:](https://leetcode.com/problems/linked-list-cycle/) |

linked-list-cycle.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Two Pointers
2+
const hasCycle = (head) => {
3+
let slow = (fast = head);
4+
5+
while (fast && fast.next) {
6+
slow = slow.next;
7+
fast = fast.next.next;
8+
9+
if (slow == fast) return true;
10+
}
11+
12+
return false;
13+
};
14+
15+
// Using Hash Map/Set
16+
const hasCycle2 = (head) => {
17+
let visited = new Set();
18+
19+
let current = head;
20+
21+
if (!current) return false;
22+
23+
while (current) {
24+
if (visited.has(current)) return true;
25+
visited.add(current);
26+
current = current.next;
27+
}
28+
29+
return false;
30+
};

0 commit comments

Comments
 (0)