-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday29.java
More file actions
53 lines (50 loc) · 1.2 KB
/
Copy pathday29.java
File metadata and controls
53 lines (50 loc) · 1.2 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
Q1: https://bit.ly/3dyXL6m
class Solution {
// Function to find the length of a loop in the linked list.
public int countNodesinLoop(Node head) {
// Add your code here.
if(head==null||head.next==null) return 0;
Node fast=head;
Node slow=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
if(slow==fast){
int i=1;
fast=fast.next;
while(fast!=slow){
fast=fast.next;
i++;
}
return i;
}
}
return 0;
}
}
TC-o(n)
SC-O(1)
Q2: https://leetcode.com/problems/palindrome-linked-list/ class Solution {
class Solution {
public boolean isPalindrome(ListNode head) {
Stack<Integer> st =new Stack<>();
ListNode curr=head;
while(curr!=null){
st.push(curr.val);
curr=curr.next;
}
curr=head;
while(curr!=null){
if(st.peek()!=curr.val){
return false;
}
else{
st.pop();
curr=curr.next;
}
}
return true;
}
}
TC-o(n)
SC-O(n)