-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday28.java
More file actions
35 lines (34 loc) · 838 Bytes
/
Copy pathday28.java
File metadata and controls
35 lines (34 loc) · 838 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Q1: https://leetcode.com/problems/linked-list-cycle/
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow=head;
ListNode fast=head;
while(fast!=null){
if(fast.next==null){
return false;
}
fast=fast.next.next;
if(slow.next==null) return false;
slow=slow.next;
if(fast==slow)
return true;
}
return false;
}
}
TC-O(N)
SC-O(1)
// Q2: https://leetcode.com/problems/middle-of-the-linked-list/
class Solution {
public ListNode middleNode(ListNode head) {
ListNode slow=head;
ListNode fast=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow =slow.next;
}
return slow;
}
}
TC-O(N)
SC-O(1)