We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent f9e2811 commit 8c9c53fCopy full SHA for 8c9c53f
141. Linked List Cycle.java
@@ -0,0 +1,33 @@
1
+/**
2
+ * Definition for singly-linked list.
3
+ * class ListNode {
4
+ * int val;
5
+ * ListNode next;
6
+ * ListNode(int x) {
7
+ * val = x;
8
+ * next = null;
9
+ * }
10
11
+ */
12
+public class Solution {
13
+ public boolean hasCycle(ListNode head) {
14
+ // Base case
15
+ if (head == null || head.next == null)
16
+ return false;
17
+
18
+ ListNode curr_node = head;
19
+ ListNode next_node = head;
20
21
+ // Make sure next node of next_node is not null, otherwise a cycle wont do
22
+ while (next_node != null && next_node.next != null) {
23
+ curr_node = curr_node.next;
24
+ next_node = next_node.next.next;
25
26
+ // Check cycle node
27
+ if (curr_node == next_node)
28
+ return true;
29
+ }
30
31
32
33
+}
0 commit comments