Skip to content

Commit 5e1b89c

Browse files
committed
add linked list cycle solution
1 parent 177c4a4 commit 5e1b89c

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

โ€Žlinked-list-cycle/Tessa1217.java

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode(int x) {
7+
* val = x;
8+
* next = null;
9+
* }
10+
* }
11+
*/
12+
/**
13+
* head๋Š” ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ์˜ ํ—ค๋“œ๋‹ค.
14+
* ํŠน์ • ๋…ธ๋“œ๊ฐ€ ๋ฆฌ์ŠคํŠธ ๋‚ด์˜ ๋‹ค๋ฅธ ๋…ธ๋“œ์™€ next ํฌ์ธํŠธ๋ฅผ ํ†ตํ•ด ์—ฐ๊ฒฐ๋˜์–ด ์žˆ์„ ๋•Œ ์ด ๋ฆฌ์ŠคํŠธ์—๋Š” ์‚ฌ์ดํด์ด ์žˆ๋‹ค๊ณ  ํ•  ์ˆ˜ ์žˆ๋‹ค.
15+
* pos๋Š” next ํฌ์ธํ„ฐ์™€ ์—ฐ๊ฒฐ๋œ ๋…ธ๋“œ์˜ ์ธ๋ฑ์Šค๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š”๋ฐ ์“ฐ์ด๋ฉฐ pos๋Š” ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์ฃผ์–ด์ง€์ง€ ์•Š๋Š”๋‹ค.
16+
* ์ฃผ์–ด์ง„ ๋ฆฌ์ŠคํŠธ์— ์‚ฌ์ดํด์ด ์žˆ๋‹ค๋ฉด true๋ฅผ ๊ทธ๋ ‡์ง€ ์•Š๋‹ค๋ฉด false๋ฅผ ๋ฐ˜ํ™˜ํ•˜์„ธ์š”.
17+
* */
18+
public class Solution {
19+
20+
// ์‹œ๊ฐ„๋ณต์žก๋„: O(n), ๊ณต๊ฐ„๋ณต์žก๋„: O(1)
21+
public boolean hasCycle(ListNode head) {
22+
if (head == null) {
23+
return false;
24+
}
25+
26+
ListNode next = head;
27+
ListNode furtherNext = head;
28+
29+
while (furtherNext != null && furtherNext.next != null) {
30+
next = next.next;
31+
furtherNext = furtherNext.next.next;
32+
if (next == furtherNext) {
33+
return true;
34+
}
35+
}
36+
37+
return false;
38+
}
39+
40+
// head ์—†์„ ๋•Œ๊นŒ์ง€ ๊ณ„์† ํƒ์ƒ‰ ๋ฐ˜๋ณต : ์‹œ๊ฐ„๋ณต์žก๋„, ๊ณต๊ฐ„๋ณต์žก๋„ O(n)
41+
// public boolean hasCycle(ListNode head) {
42+
43+
// Set<ListNode> nodeSet = new HashSet<>();
44+
45+
// while (head != null) {
46+
// if (nodeSet.contains(head)) {
47+
// return true;
48+
// }
49+
// nodeSet.add(head);
50+
// head = head.next;
51+
// }
52+
53+
// return false;
54+
55+
// }
56+
}
57+

0 commit comments

Comments
ย (0)