Skip to content

Commit 659bf6e

Browse files
committed
solve: linked list cycle
1 parent 76fe4b5 commit 659bf6e

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

linked-list-cycle/wogha95.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Floyd tortoise and hare 알고리즘을 바탕으로
3+
* 한칸씩 이동하는 포인터와 2칸씩 이동하는 포인터는 결국에 만난다는 점을 이용해서 품
4+
*
5+
* TC: O(N)
6+
* SC: O(1)
7+
* N: linked list length
8+
*/
9+
10+
/**
11+
* Definition for singly-linked list.
12+
* function ListNode(val) {
13+
* this.val = val;
14+
* this.next = null;
15+
* }
16+
*/
17+
18+
/**
19+
* @param {ListNode} head
20+
* @return {boolean}
21+
*/
22+
var hasCycle = function (head) {
23+
let oneStep = head;
24+
let twoStep = head;
25+
26+
while (twoStep && twoStep.next) {
27+
if (oneStep === twoStep) {
28+
return true;
29+
}
30+
31+
oneStep = oneStep.next;
32+
twoStep = twoStep.next.next;
33+
}
34+
35+
return false;
36+
};

0 commit comments

Comments
 (0)