Skip to content

Commit 7bc75e5

Browse files
committed
liked list cycle solution
1 parent 6fda5a7 commit 7bc75e5

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val) {
4+
* this.val = val;
5+
* this.next = null;
6+
* }
7+
*/
8+
9+
/**
10+
* @param {ListNode} head
11+
* @return {boolean}
12+
*/
13+
var hasCycle = function (head) {
14+
// ๋ฆฌ์ŠคํŠธ๊ฐ€ ๋น„์–ด ์žˆ๊ฑฐ๋‚˜ ๋…ธ๋“œ๊ฐ€ ํ•˜๋‚˜๋ฟ์ด๋ฉด ์‚ฌ์ดํด์ด ์žˆ์„ ์ˆ˜ ์—†์Œ
15+
if (!head || !head.next) return false;
16+
17+
// ๋‘ ํฌ์ธํ„ฐ ์ดˆ๊ธฐํ™”: slow๋Š” ํ•œ ์นธ์”ฉ, fast๋Š” ๋‘ ์นธ์”ฉ ์ด๋™
18+
let slow = head;
19+
let fast = head.next;
20+
21+
// fast์™€ slow๊ฐ€ ๋งŒ๋‚  ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณต
22+
while (fast !== slow) {
23+
// fast๊ฐ€ ๋์— ๋„๋‹ฌํ•˜๋ฉด ์‚ฌ์ดํด์ด ์—†์Œ
24+
if (!fast || !fast.next) return false;
25+
26+
// slow๋Š” ํ•œ ์นธ ์ด๋™
27+
slow = slow.next;
28+
// fast๋Š” ๋‘ ์นธ ์ด๋™
29+
fast = fast.next.next;
30+
}
31+
32+
// fast์™€ slow๊ฐ€ ๋งŒ๋‚ฌ๋‹ค๋ฉด ์‚ฌ์ดํด์ด ์žˆ์Œ
33+
return true;
34+
};

0 commit comments

Comments
ย (0)