Skip to content

Commit 031db5d

Browse files
author
แ„‹แ…ตแ„‹แ…งแ†ซแ„‰แ…ฎ
committed
linked list cycle
1 parent 5d40f2b commit 031db5d

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package leetcode_study
2+
3+
/*
4+
* ๋งํฌ๋“œ ๋ฆฌ์ŠคํŠธ์—์„œ ์ˆœํ™˜์ด ๋ฐœ์ƒํ•˜๋Š”์ง€ ์ฒดํฌํ•˜๋Š” ๋ฌธ์ œ
5+
* Node `val` ๊ฐ’์„ ์ฃผ์–ด์ง„ ๋ฒ”์œ„ (-10,000 <= `val` <= 10,000) ๋ณด๋‹ค ํฐ ์ •์ˆ˜๋กœ ๋ณ€๊ฒฝํ•ด cycle ํŒ๋ณ„ ์‹œ๋„
6+
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n)
7+
* -> linked list node ๊ฐœ์ˆ˜๋งŒํผ ์ง„ํ–‰
8+
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(1)
9+
* -> ์ฃผ์–ด์ง„ node๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” currentNode ์ด์™ธ์— ์ถ”๊ฐ€๋˜๋Š” ์—†์Œ
10+
* */
11+
fun hasCycle(head: ListNode?): Boolean {
12+
var currentNode = head
13+
14+
while (currentNode?.next != null) {
15+
if (currentNode.`val` == 10001) return true // ์ด๋ฏธ ๋ฐฉ๋ฌธํ•œ ๋…ธ๋“œ์ด๋ฉด ์‚ฌ์ดํด ์กด์žฌ
16+
currentNode.`val` = 10001 // ๋ฐฉ๋ฌธํ•œ ๋…ธ๋“œ ํ‘œ์‹œ
17+
currentNode = currentNode.next // ๋‹ค์Œ ๋…ธ๋“œ๋กœ ์ด๋™
18+
}
19+
20+
return false // `null`์„ ๋งŒ๋‚ฌ๋‹ค๋ฉด ์‚ฌ์ดํด ์—†์Œ
21+
}

0 commit comments

Comments
ย (0)