Skip to content

Commit 336c4cd

Browse files
committed
add Linked List Cycle solution
1 parent 1087be0 commit 336c4cd

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

linked-list-cycle/HoonDongKang.ts

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* [Problem]: [141] Linked List Cycle
3+
* (https://leetcode.com/problems/linked-list-cycle/description/)
4+
*/
5+
class ListNode {
6+
val: number;
7+
next: ListNode | null;
8+
constructor(val?: number, next?: ListNode | null) {
9+
this.val = val === undefined ? 0 : val;
10+
this.next = next === undefined ? null : next;
11+
}
12+
}
13+
14+
function hasCycle(head: ListNode | null): boolean {
15+
//시간복잡도 O(n)
16+
//공간복잡도 O(n)
17+
function setFunc(head: ListNode | null): boolean {
18+
if (!head) return false;
19+
const set = new Set<ListNode>();
20+
let currentNode: ListNode = head;
21+
22+
while (currentNode) {
23+
if (set.has(currentNode)) return true;
24+
25+
set.add(currentNode);
26+
currentNode = currentNode.next!;
27+
}
28+
29+
return false;
30+
}
31+
//시간복잡도 O(n)
32+
//공간복잡도 O(1)
33+
function pointerFunc(head: ListNode | null): boolean {
34+
let slow = head;
35+
let fast = head;
36+
while (fast && fast.next) {
37+
slow = slow.next;
38+
fast = fast.next.next;
39+
40+
if (slow === fast) return true;
41+
}
42+
return false;
43+
}
44+
}

0 commit comments

Comments
 (0)