File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change 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+
You canโt perform that action at this time.
0 commit comments