Skip to content

Commit 0379094

Browse files
refactor 141
1 parent 816788e commit 0379094

File tree

2 files changed

+50
-3
lines changed

2 files changed

+50
-3
lines changed

src/main/java/com/fishercoder/solutions/_141.java

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,28 @@
88
/**
99
* 141. Linked List Cycle
1010
11-
Given a linked list, determine if it has a cycle in it.
11+
Given a linked list, determine if it has a cycle in it.
12+
To represent a cycle in the given linked list, we use an integer
13+
pos which represents the position (0-indexed) in the linked list where tail connects to.
14+
If pos is -1, then there is no cycle in the linked list.
1215
13-
Follow up:
14-
Can you solve it without using extra space?
16+
Example 1:
17+
Input: head = [3,2,0,-4], pos = 1
18+
Output: true
19+
Explanation: There is a cycle in the linked list, where tail connects to the second node.
20+
21+
Example 2:
22+
Input: head = [1,2], pos = 0
23+
Output: true
24+
Explanation: There is a cycle in the linked list, where tail connects to the first node.
25+
26+
Example 3:
27+
Input: head = [1], pos = -1
28+
Output: false
29+
Explanation: There is no cycle in the linked list.
30+
31+
Follow up:
32+
Can you solve it using O(1) (i.e. constant) memory?
1533
*/
1634
public class _141 {
1735

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.common.utils.LinkedListUtils;
4+
import com.fishercoder.solutions._141;
5+
import org.junit.BeforeClass;
6+
import org.junit.Test;
7+
8+
import static org.junit.Assert.assertEquals;
9+
10+
public class _141Test {
11+
private static _141.Solution1 solution1;
12+
private static _141.Solution2 solution2;
13+
14+
@BeforeClass
15+
public static void setup() {
16+
solution1 = new _141.Solution1();
17+
solution2 = new _141.Solution2();
18+
}
19+
20+
@Test
21+
public void test1() {
22+
assertEquals(false, solution1.hasCycle(LinkedListUtils.contructLinkedList(new int[]{1, 2, 3, 4})));
23+
}
24+
25+
@Test
26+
public void test2() {
27+
assertEquals(false, solution2.hasCycle(LinkedListUtils.contructLinkedList(new int[]{1, 2, 3, 4})));
28+
}
29+
}

0 commit comments

Comments
 (0)