-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday29.java
More file actions
73 lines (53 loc) · 1.59 KB
/
day29.java
File metadata and controls
73 lines (53 loc) · 1.59 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//ques1:Find length of Loop
//link:https://www.geeksforgeeks.org/problems/find-length-of-loop/1
class Solution {
// Function to find the length of a loop in the linked list.
public int countNodesinLoop(Node head) {
Node hare = head;
Node turtle = head;
while (hare != null && hare.next != null) {
turtle = turtle.next;
hare = hare.next.next;
if (hare == turtle) {
return countLoopNodes(turtle);
}
}
return 0;
}
private int countLoopNodes(Node node) {
int count = 1;
Node temp = node;
while (temp.next != node) {
count++;
temp = temp.next;
}
return count;
}
}
//ques2:Palindrome Linked List
//link:https://www.geeksforgeeks.org/problems/check-if-linked-list-is-pallindrome/1
class Solution {
// Function to check whether the list is a palindrome.
static boolean isPalindrome(Node head) {
if (head == null || head.next == null) {
return true;
}
Node slow = head, fast = head;
Stack<Integer> stack = new Stack<>();
while (fast != null && fast.next != null) {
stack.push(slow.data);
slow = slow.next;
fast = fast.next.next;
}
if (fast != null) {
slow = slow.next;
}
while (slow != null) {
if (slow.data != stack.pop()) {
return false;
}
slow = slow.next;
}
return true;
}
}