Skip to content

Commit 7aae088

Browse files
committed
linked list cycle
1 parent ab500f9 commit 7aae088

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
๊ธธ์ด๊ฐ€ ์ตœ๋Œ€ 10000์ด๋ฏ€๋กœ 10001๊นŒ์ง€ ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๋Œ์•„ ํ™•์ธํ•˜๋Š” ๋ฐฉ๋ฒ•
3+
*/
4+
public class Solution {
5+
public boolean hasCycle(ListNode head) {
6+
int max = 10001;
7+
int idx = 0;
8+
boolean result = false;
9+
while(head != null) {
10+
idx++;
11+
head = head.next;
12+
if(idx > max) {
13+
result = true;
14+
break;
15+
}
16+
}
17+
18+
return result;
19+
}
20+
}
21+
/**
22+
2๊ฐœ์˜ ํฌ์ธํ„ฐ๋ฅผ ์ด์šฉํ•˜์—ฌ, ๋งŒ๋‚˜๋Š”์ง€ ํ™•์ธํ•˜๋Š” ๋ฐฉ๋ฒ•
23+
*/
24+
public class Solution2 {
25+
public boolean hasCycle(ListNode head) {
26+
ListNode first = head;
27+
ListNode second = head;
28+
boolean result = false;
29+
while(second != null && second.next != null) {
30+
first = first.next;
31+
second = second.next.next;
32+
if(first == second) {
33+
result = true;
34+
break;
35+
}
36+
}
37+
38+
return result;
39+
}
40+
}

0 commit comments

Comments
ย (0)