Skip to content

Commit c988e63

Browse files
authored
[ PS ] : Linked List Cycle
1 parent c523446 commit c988e63

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val) {
4+
* this.val = val;
5+
* this.next = null;
6+
* }
7+
*/
8+
9+
/**
10+
* ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ์˜ ์‚ฌ์ดํด ์—ฌ๋ถ€๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜
11+
* ์‹œ๊ฐ„๋ณต์žก๋„: O(n)
12+
* ๊ณต๊ฐ„๋ณต์žก๋„: O(1)
13+
* @param {ListNode} head
14+
* @return {boolean}
15+
*/
16+
const hasCycle = function(head) {
17+
let node = head;
18+
19+
while (node?.next) {
20+
if (node.val === null) {
21+
return true;
22+
}
23+
node.val = null;
24+
node = node.next;
25+
}
26+
27+
return false;
28+
};
29+
30+
// ๊ฑฐ๋ถ์ด์™€ ํ† ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜
31+
// ์‹œ๊ฐ„๋ณต์žก๋„: O(n)
32+
// ๊ณต๊ฐ„๋ณต์žก๋„: O(1)
33+
const hasCycle = function(head) {
34+
let slow = head; // ํ•œ ๋ฒˆ์— ํ•œ ๋…ธ๋“œ์”ฉ
35+
let fast = head; // ํ•œ ๋ฒˆ์— ๋‘ ๋…ธ๋“œ์”ฉ
36+
37+
while (fast?.next) {
38+
slow = slow.next;
39+
fast = fast.next.next;
40+
41+
// ํ•œ ๋ฒˆ์— ๋‘ ๋…ธ๋“œ์”ฉ ๊ฐ€๋Š” fast๊ฐ€
42+
// ์ž์‹ ๋ณด๋‹ค ๋А๋ฆฐ slow๋ž‘ ๊ฐ™์€ ๊ฒฝ์šฐ๊ฐ€ ์ƒ๊ธด๋‹ค๋ฉด
43+
// ์‚ฌ์ดํด์ด ์žˆ๋‹ค๋Š” ๋œป
44+
if (slow === fast) {
45+
return true;
46+
}
47+
}
48+
49+
return false;
50+
};

0 commit comments

Comments
ย (0)