Skip to content

Commit 0def0e3

Browse files
solves linkedlist cycle ii in java
1 parent 93310dd commit 0def0e3

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@
126126
| 138 | [Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer) | [![Java](assets/java.png)](src/CopyListWithRandomPointer.java) | |
127127
| 139 | [Word Break](https://leetcode.com/problems/word-break) | [![Java](assets/java.png)](src/WordBreak.java) | |
128128
| 141 | [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle) | [![Java](assets/java.png)](src/LinkedListCycle.java) [![Python](assets/python.png)](python/linked_list_cycle.py) | |
129-
| 142 | [Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii) | | |
129+
| 142 | [Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii) | [![Java](assets/java.png)](src/LinkedListCycleII.java) | |
130130
| 143 | [Reorder List](https://leetcode.com/problems/reorder-list) | | |
131131
| 144 | [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal) | [![Java](assets/java.png)](src/BinaryTreePreOrderTraversal.java) [![Python](assets/python.png)](python/binary_tree_preorder_traversal.py) | |
132132
| 145 | [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal) | [![Java](assets/java.png)](src/BinaryTreePostorderTraversal.java) [![Python](assets/python.png)](python/binary_tree_postorder_traversal.py) | |

Diff for: src/LinkedListCycleII.java

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// https://leetcode.com/problems/linked-list-cycle-ii
2+
// T: O(n)
3+
// S: O(1)
4+
5+
public class LinkedListCycleII {
6+
public ListNode detectCycle(ListNode head) {
7+
if (head == null) return null;
8+
9+
ListNode slow = head, fast = head, entry = head;
10+
while (fast.next != null && fast.next.next != null) {
11+
slow = slow.next;
12+
fast = fast.next.next;
13+
14+
if (slow == fast) {
15+
while (entry != slow) {
16+
entry = entry.next;
17+
slow = slow.next;
18+
}
19+
return entry;
20+
}
21+
}
22+
return null;
23+
}
24+
}

0 commit comments

Comments
 (0)