Skip to content

Commit 9fb24b3

Browse files
committed
1 parent 24739e2 commit 9fb24b3

File tree

2 files changed

+106
-0
lines changed

2 files changed

+106
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package linkedlist;
2+
3+
public class LinkedListCycle {
4+
5+
public boolean hasCycle(ListNode head) {
6+
7+
ListNode faster = head;
8+
ListNode slower = head;
9+
10+
while (faster != null && faster.next != null) {
11+
12+
faster = faster.next;
13+
if (faster == slower) return true;
14+
15+
faster = faster.next;
16+
if (faster == null) return false;
17+
if (faster == slower) return true;
18+
19+
slower = slower.next;
20+
}
21+
22+
return false;
23+
}
24+
25+
public static class ListNode {
26+
27+
public int val;
28+
public ListNode next;
29+
30+
public ListNode(int x) {
31+
val = x;
32+
next = null;
33+
}
34+
}
35+
}
36+
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package linkedlist;
2+
3+
import lombok.val;
4+
import org.junit.Test;
5+
6+
import static org.junit.Assert.assertFalse;
7+
import static org.junit.Assert.assertTrue;
8+
9+
public class LinkedListCycleTest {
10+
11+
@Test
12+
public void hasCycleExample1() {
13+
14+
// given: 3 -> 2 -> 0 -> -4 -> 2(cycle)
15+
val node1 = new LinkedListCycle.ListNode(3);
16+
val node2 = new LinkedListCycle.ListNode(2);
17+
val node3 = new LinkedListCycle.ListNode(0);
18+
val node4 = new LinkedListCycle.ListNode(-4);
19+
node1.next = node2;
20+
node2.next = node3;
21+
node3.next = node4;
22+
node4.next = node2;
23+
24+
// when
25+
val hasCycle = new LinkedListCycle().hasCycle(node1);
26+
27+
// then
28+
assertTrue(hasCycle);
29+
}
30+
31+
@Test
32+
public void hasCycleExample2() {
33+
34+
// given: 1 -> 2 -> 1(cycle)
35+
val node1 = new LinkedListCycle.ListNode(1);
36+
val node2 = new LinkedListCycle.ListNode(2);
37+
node1.next = node2;
38+
node2.next = node1;
39+
40+
// when
41+
val hasCycle = new LinkedListCycle().hasCycle(node1);
42+
43+
// then
44+
assertTrue(hasCycle);
45+
}
46+
47+
@Test
48+
public void hasCycleExample3() {
49+
50+
// given: 1
51+
val node1 = new LinkedListCycle.ListNode(1);
52+
53+
// when
54+
val hasCycle = new LinkedListCycle().hasCycle(node1);
55+
56+
// then
57+
assertFalse(hasCycle);
58+
}
59+
60+
@Test
61+
public void hasCycleWhenHeadIsNull() {
62+
63+
// when
64+
val hasCycle = new LinkedListCycle().hasCycle(null);
65+
66+
// then
67+
assertFalse(hasCycle);
68+
}
69+
70+
}

0 commit comments

Comments
 (0)