forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPalindromeSinglyLinkedList.java
75 lines (66 loc) · 1.92 KB
/
PalindromeSinglyLinkedList.java
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
74
75
package com.thealgorithms.misc;
import java.util.Stack;
/**
* A simple way of knowing if a singly linked list is palindrome is to push all
* the values into a Stack and then compare the list to popped vales from the
* Stack.
*
* See more:
* https://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/
*/
public final class PalindromeSinglyLinkedList {
private PalindromeSinglyLinkedList() {
}
public static boolean isPalindrome(final Iterable linkedList) {
var linkedListValues = new Stack<>();
for (final var x : linkedList) {
linkedListValues.push(x);
}
for (final var x : linkedList) {
if (x != linkedListValues.pop()) {
return false;
}
}
return true;
}
// Optimised approach with O(n) time complexity and O(1) space complexity
public static boolean isPalindromeOptimised(Node head) {
if (head == null || head.next == null) {
return true;
}
Node slow = head;
Node fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
Node midNode = slow;
Node prevNode = null;
Node currNode = midNode;
Node nextNode;
while (currNode != null) {
nextNode = currNode.next;
currNode.next = prevNode;
prevNode = currNode;
currNode = nextNode;
}
Node left = head;
Node right = prevNode;
while (left != null && right != null) {
if (left.val != right.val) {
return false;
}
right = right.next;
left = left.next;
}
return true;
}
static class Node {
int val;
Node next;
Node(int val) {
this.val = val;
this.next = null;
}
}
}